Explanation in the document: https://docs.python.org/2/library/weakref.html
Interpretation in wiki: in computer programming, weak references, compared with strong references, mean that the referenced objects cannot be referenced by the garbage collector. If an object is referenced by a weak reference, it is considered inaccessible (or weak accessible) and may be recycled at any time. The main function is to reduce the number of unnecessary objects in memory.
For more details, see Wikipedia.
Easy to understand:
The garbage collection mechanism in python is to reference counters. When the reference number of an object is 0, it will be recycled from the memory. Garbage collection becomes unreliable when circular references occur.
Compare by a piece of code:
#-*-Encoding = UTF-8-*-''' Author: orangleliupython small experiment with weak references ''' import weakrefimport gcclass newobj (object): def my_method (Self ): print "called me" OBJ = newobj () r = weakref. ref (OBJ) GC. collect () print R () is objobj = 1gc. collect () # print R () is none, R () print ******************** 'obj = newobj () S = objgc. collect () print S is objobj = 1gc. collect () print S is none, S
Comparison result:
True
True none
*******************
True
False <__ main _. newobj object at 0x024fb870>
It is easy to see that the weak reference counter does not increase, so when OBJ does not reference newobj, The newobj object is released, so the reference object of R is gone. The S object is the same as the referenced object we usually use. When S = OBJ, the reference counter is + 1. So when obj is not pointed to newobj, s still points to newobj, the reference count for newobj is 2-1 = 1.
Through the experiment we can see the principle, can this weak reference in what specific circumstances to use it, how to avoid the circular reference, you can refer to the case of pymeng W: http://pymotw.com/2/weakref/
This problem has not been solved in actual development, and will be used for further research.
This article from the "orangleliu notebook" blog, reprint please be sure to keep this source http://blog.csdn.net/orangleliu/article/details/40718121
Orangleliu
[Pyhton] weakref weak reference