zoukankan      html  css  js  c++  java
  • python的WeakKeyDictionary类和weakref模块的其他函数

    python的WeakKeyDictionary类和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('销毁a1对象前')
    for item in wd.items():
        nb_print(item)
    
    
    del a1
    nb_print('销毁a1对象后')
    for item in wd.items():
        nb_print(item)

    while 1:
    time.sleep(10) # 阻止退出触发del,导致不方便观察

     使用普通dict

    使用 weakref.WeakKeyDictionary对比使用普通字典,可以看到不同的地方是销毁a1后,普通字典中还有a1这个键,并且del a1时 无法触发A类的__del__方法,。

    除此之外还有weakvaluedictionary和weakset这些对象。

    weakref里面的函数。

    class TestObj:
        def __init__(self):
            self.xx = 666
    
    
    def test_func(reference):
        nb_print('Hello from Callback function!')
    
        nb_print(reference, 'This weak reference is no longer valid')
    
    
    t = TestObj()
    
    # 建立一个a的弱引用
    nb_print(t.xx)
    t_ref = weakref.ref(t, test_func)
    nb_print(t_ref().xx)
    t.xx = 777
    nb_print(t_ref().xx)
    
    del t
    nb_print(t_ref().xx)   # 可以发现用不了了。
  • 相关阅读:
    微博粉丝服务---“公众号”开发
    springboot --- 之SSM框架整合
    Android 接收短信
    数字币开发相关
    boot camp要求独立的fat分区
    u盘安装 osx 出现 “不能验证”
    微软驱动签名
    centos7 安装 isign
    用windbg查看dmp文件,定位bug位置
    H5移动端,ios从后台返回到app,页面会白一下
  • 原文地址:https://www.cnblogs.com/ydf0509/p/11016292.html
Copyright © 2011-2022 走看看