Other functions of the python WeakKeyDictionary classes and modules weakref

Other functions of the python WeakKeyDictionary classes and modules weakref

 

# -*- coding: utf-8 -*-
# @Author  : ydf
# @Time    : 2019/6/13 13:18
import time
import weakref
from app.utils_ydf import nb_print
class A():
    def __init__(self,x):
        self._x = x

    def __repr__(self):
        return f'A类的{self._x}实例 {id(self)}'

    def __del__(self):
        nb_print(f'摧毁啦 {self._x} 。。。。')


wd = dict()
# WD = weakref.WeakKeyDictionary () 

a1 = A (. 1 ) 
A2 = A (2 ) 



WD [a1] = ' XXXXXXX ' 
WD [A2] = ' yyyyyyy ' 

nb_print ( ' before the destruction of the object a1 ' )
 for Item in WD. items (): 
    nb_print (Item) 


del a1 
nb_print ( ' after the destruction of the object a1 ' )
 for Item in wd.items (): 
    nb_print (Item) 

the while 1:
the time.sleep (10) # exit stop triggering del, resulting in convenient Observed

 Use common dict

 

Use weakref.WeakKeyDictionary contrast to the use of ordinary dictionary, you can see different places after the destruction of a1, a1 ordinary dictionary as well as the key, and it can not trigger __del__ A class method when del a1,.

 

 

In addition there weakvaluedictionary and weakset these objects.

 

 

 

Function weakref inside.

 

class TestObj:
     DEF  the __init__ (Self): 
        self.xx = 666 DEF test_func (Reference): 
    (nb_print ' ! the Callback function from the Hello ' ) 
    nb_print (Reference, ' This weak Reference IS NO longer Valid ' ) 
T = TestObj () # establishing a reference to a weak nb_print (t.xx) 
t_ref in = weakref.ref (T, test_func) 
nb_print (t_ref in (). XX) 
t.xx = 777 
nb_print (t_ref in (). XX) del T 
nb_print (t_ref in () .xx)    # can be found not working.










 

Guess you like

Origin www.cnblogs.com/ydf0509/p/11016292.html
Recommended