Case:
In Python, garbage objects are recycled by reference counting, in some circular data structures (trees, graphs ...). ), there is a circular reference between objects, such as the parent node of the tree refers to the child nodes, the child nodes refer to the parent node at the same time, the two objects can not be immediately released by dropping the reference child node.
Requirements:
How do I resolve this kind of memory management problem?
How do I query the reference count of an object?
Import Sys
Sys.getrefcount (obj)
# Query reference count must be more than 1 because object also references query object
How do I troubleshoot memory management issues?
- By Weakref, a weak reference is made, and when Del is no longer referenced, add weakref.ref (Reference obj) to the reference party,
- When using references, you need to use the form of a function call
#!/usr/bin/python3import weakrefimport sysclass Data (object): def __init__ (self, value, owner): self.value = Value # declares a weak reference, the owner of the node class itself Self.owner = weakref.ref (owner) # accesses the reference object by means of a function call def __str__ (self): return "%s ' data, value is%s"% (Self.owner (), Self.value) def __del__ (self): print (' in_data.__del__ ') Class Node (object): def __init__ (self, value): # Pass the class itself, also as a parameter, into the data class Self.data = Data # custom object name, easy to identify def __str__ (self): return ' Node ' def __del__: print (' in_node.__del__ ') if __name__ = = ' __main__ ': node = node (+) print (node.data) # Prints the reference count of the Node object print ( Sys.getrefcount (node)-1) # When the node object is deleted, the data instance object is also disposed in reference 0 to release del node input (' del done >>> >> ')
Python_ How to manage memory in a circular reference?