您的位置:首页 > 编程语言 > Python开发

python的垃圾回收机制

2013-03-28 16:41 225 查看
学习自《Python开发技术详解》
# 使用gc模块显示的调用垃圾回收器。

import gc

class Fruit:
def __init__(self, name, color):
self.__name = name
self.__color = color

def getColor(self):
return self.__color

def setColor(self, color):
self.__color = color

def getName(self):
return self.__name

def setColor(self, name):
self.__name = name

class FruitShop:
def __init__(self):
self.fruit = []

def addFruit(self, fruit):
fruit.parent = self
self.fruit.append(fruit)

if __name__ == "__main__":
shop = FruitShop()
shop.addFruit(Fruit("apple", "red"))
shop.addFruit(Fruit("banana", "yellow"))
print gc.get_referrers(shop)
del shop
print gc.collect()


Java 中没有提供析构函数,而是采用垃圾回收机制清理不再使用的对象。Python也采用垃圾回收机制清除对象,Python提供了gc模块释放不再使用的对象。。垃圾回收机制有许多种算法,Python采用的是引用计数的方式。当某个对象在其作用域内不再被其他对象引用时,Python就会自动清除该对象。垃圾回收机制很好的避免了内存泄漏的发生。函数colllect()可以一次性收集所有待处理的对象。

运行结果:

C:\Python27\python.exeD:/Documents/PycharmProjects2013/PythonKaiFaJSXJ/Pydemo.py

[{'_Fruit__name': 'apple', 'parent':<__main__.FruitShop instance at 0x01BD3C60>, '_Fruit__color': 'red'},{'_Fruit__name': 'banana', 'parent': <__main__.FruitShop instance at0x01BD3C60>, '_Fruit__color': 'yellow'}, {'shop': <__main__.FruitShopinstance at
0x01BD3C60>, 'FruitShop': <class __main__.FruitShop at0x0138CB58>, '__builtins__': <module '__builtin__' (built-in)>,'__file__': 'D:/Documents/PycharmProjects2013/PythonKaiFaJSXJ/Pydemo.py','__package__': None, 'Fruit': <class __main__.Fruit at 0x012F6A78>,
'gc':<module 'gc' (built-in)>, '__name__': '__main__', '__doc__': None}]

7

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: