How does python manage memory in loop references? python references
In python, junk objects are recycled by reference counting. In some ring data structures (tree, graph ......), There is a circular reference between objects. For example, if the parent node of the tree references the child node, the child node references the parent node at the same time. In this case, the parent and child nodes are referenced through del, and the two objects cannot be released immediately.
Requirements:
How to solve such memory management problems?
How can I query the reference count of an object?
Import sys
Sys. getrefcount (obj)
# The query reference count must be 1, because the object also references the query object.
How to solve the memory management problem?
- Use weakref to perform weak references. When del is used, weakref. ref (reference obj) is not referenced );
- Function call is required when reference is used.
#! /Usr/bin/python3 import weakrefimport sys class Data (object): def _ init _ (self, value, owner): self. value = value # declare weak references. The owner is the Node class itself self. owner = weakref. ref (owner) # access the reference object 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 as a parameter to self in the Data class. data = Data (value, self) # custom object name, easy to recognize def _ str _ (self): return 'node' def _ del _ (self ): print ('in _ node. _ del _ ') if _ name _ =' _ main _ ': node = Node (100) print (node. data) # print the reference count of the node object print (sys. getrefcount (node)-1) # When deleting a node object, the Data instance object will release del node input ('del done >>>> ') when the reference value is 0 ')
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.