Home >Backend Development >Python Tutorial >How python manages memory in circular references

How python manages memory in circular references

小云云
小云云Original
2018-03-29 14:15:212612browse

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 >>>>>')
  • Related recommendations:

PHP management memory function memory_get_usage() introduction_PHP tutorial



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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn