Home >Backend Development >Python Tutorial >How python manages memory in circular references
In python, garbage objects are recycled through reference counting. In some circular data structures (trees, graphs...), there are circular references between objects. For example, the parent node of the tree refers to the child node, and the child node also refers to the parent node. At this time, by deleting the reference to the parent and child nodes, the two objects cannot be released immediately.
Requirements:
How to solve this kind of memory management problem?
How to query the reference count of an object?
####How to solve memory management problems?
Make a weak reference through weakref. When del, no longer reference, add weakref.ref (reference obj) on the referencing side;When using references, you need to use the form of function calls
#!/usr/bin/python3 import weakref import sys class Data(object): def __init__(self, value, owner): self.value = value # 声明弱引用,owner为Node类本身 self.owner = weakref.ref(owner) # 通过函数调用的方式访问引用对象 def __str__(self): return "%s's data, value is %s" % (self.owner(), self.value) def __del__(self): print('in_data.__del__') class Node(object): def __init__(self, value): # 把类本身,也当做参数传入Data类中 self.data = Data(value, self) # 自定义对象名,容易辨认 def __str__(self): return 'Node' def __del__(self): print('in_node.__del__') if __name__ == '__main__': node = Node(100) print(node.data) # 打印node对象的引用计数 print(sys.getrefcount(node) - 1) # 当删除node对象时候,Data实例对象在引用计算为0也相应释放 del node input('del done >>>>>')
The above is the detailed content of How python manages memory in circular references. For more information, please follow other related articles on the PHP Chinese website!