Python静态变量列表__del__
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python静态变量列表__del__,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2116字,纯文字阅读大概需要4分钟。
内容图文
![Python静态变量列表__del__](/upload/InfoBanner/zyjiaocheng/733/82c0a526172644b097c06068bbaac61e.jpg)
我正在尝试使用静态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__(除非你让其他变量指向同一个对象,比如做一个分配).
内容总结
以上是互联网集市为您收集整理的Python静态变量列表__del__全部内容,希望文章能够帮你解决Python静态变量列表__del__所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。