ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python静态变量列表__del__

2019-08-25 08:56:48  阅读:293  来源: 互联网

标签:static-variables del python list methods


我正在尝试使用静态List创建一个类,它收集对象类的所有新实例.我面临的问题,似乎只要我尝试以与整数相同的方式使用列表,我就不能再使用魔术标记__del__了.

我的例子:

class MyClass(object):  

    count = 0
    #instances = []

    def __init__(self, a, b):
        self.a = a
        self.b = b
        MyClass.count += 1
        #MyClass.instances.append(self)

    def __str__(self):
        return  self.__repr__()

    def __repr__(self):
        return "a: " + str(self.a) + ", b: " + str(self.b)

    def __del__(self):
        MyClass.count -= 1
        #MyClass.instances.remove(self)

A = MyClass(1,'abc')
B = MyClass(2,'def')
print MyClass.count
del B
print MyClass.count

有了评论,我得到了正确答案:

2
1

但没有评论 – 包括现在的静态对象列表MyClass.instances我得到了错误的答案:

2
2

似乎MyClass不再能够达到它的__del__方法了!怎么会?

解决方法:

docs,

del x doesn’t directly call x.__del__() — the former decrements the reference
count for x by one, and the latter is only called when x‘s reference count
reaches zero. 

当你取消评论时,

instances = []
...
...
MyClass.instances.append(self)

您正在MyClass.instances中存储对当前Object的引用.这意味着,引用计数在内部递增1.这就是为什么不立即调用__del__.

若要解决此问题,请从列表中明确删除该项目

MyClass.instances.remove(B)
del B

现在它将打印出来

2
1

正如所料.

还有一种方法可以解决这个问题.那就是使用weakref.从docs开始,

A weak reference to an object is not enough to keep the object alive:
when the only remaining references to a referent are weak references,
garbage collection is free to destroy the referent and reuse its
memory for something else. A primary use for weak references is to
implement caches or mappings holding large objects, where it’s desired
that a large object not be kept alive solely because it appears in a
cache or mapping.

因此,拥有weakref不会推迟对象的删除.使用weakref,可以像这样修复

MyClass.instances.append(weakref.ref(self))
...
...
# MyClass.instances.remove(weakref.ref(self))
MyClass.instances = [w_ref for w_ref in MyClass.instances if w_ref() is None]

我们可以调用每个weakref对象而不是使用remove方法,如果它们返回None,它们就已经死了.所以,我们用列表理解来过滤它们.

所以,现在,当你说del B时,即使B存在weakrefs,它也会调用__del__(除非你让其他变量指向同一个对象,比如做一个分配).

标签:static-variables,del,python,list,methods
来源: https://codeday.me/bug/20190825/1717418.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有