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
相关文章推荐
- Python垃圾回收机制
- Python的垃圾回收机制(一)之简介
- python知识点4之垃圾回收机制
- Python垃圾回收机制及gc理解
- 24-python_内部类-构造函数与析构函数-垃圾回收机制
- Python垃圾回收机制
- python-垃圾回收机制
- Python 垃圾回收机制详解
- 深入分析 Python 的垃圾回收机制
- Python的垃圾回收机制深入分析
- 理解Python垃圾回收机制
- Python的垃圾回收机制
- 深入分析 Python 的垃圾回收机制
- python和ruby的垃圾回收机制
- python的垃圾回收机制
- Python垃圾回收机制
- Python的垃圾回收机制
- Python 构造函数、 Python 析构函数、Python 垃圾回收机制
- python垃圾回收机制
- python垃圾回收机制及调优