Python weakref回调和__del__执行顺序
作者:互联网
在Python中,有没有办法在对象完成后调用函数?
我认为弱反射中的回调会这样做,但是一旦对象被垃圾收集,但是在调用对象__del__方法之前,看起来会调用weakref的回调.这似乎与the notes on weakrefs and garbage collection in the Python trunk相反.这是一个例子.
import sys
import weakref
class Spam(object) :
def __init__(self, name) :
self.name = name
def __del__(self) :
sys.stdout.write("Deleting Spam:%s\n" % self.name)
sys.stdout.flush()
def cleaner(reference) :
sys.stdout.write("In callback with reference %s\n" % reference)
sys.stdout.flush()
spam = Spam("first")
wk_spam = weakref.ref(spam, cleaner)
del spam
我得到的输出是
$python weakref_test.py
In callback with reference <weakref at 0xc760a8; dead>
Deleting Spam:first
还有其他传统方式可以做我想要的吗?我可以以某种方式强制完成我的回调吗?
解决方法:
如果“做你想做的事”意味着“当资源离开上下文时运行代码”(而不是,例如,“滥用垃圾收集器来做事情”),你看错了方向. Python将整个想法简化为context-managers,与with语句一起使用.
from __future__ import with_statement
import sys
class Spam(object):
def __init__(self, name):
self.name = name
def __enter__(self):
sys.stdout.write("Entering Spam:%s\n" % self.name)
sys.stdout.flush()
def __exit__(self, type, value, traceback):
sys.stdout.write("Lets clean up Spam:%s\n" % self.name)
if type is None:
sys.stdout.write("Leaving Spam:%s in peace\n" % self.name)
return
else:
sys.stdout.write("Leaving Spam:%s with Exception:%r\n" % (self.name, value))
with Spam("first") as spam:
pass
with Spam("2nd") as spam:
raise Exception("Oh No!")
得到:
Entering Spam:first
Lets clean up Spam:first
Leaving Spam:first in peace
Entering Spam:2nd
Lets clean up Spam:2nd
Leaving Spam:2nd with Exception:Exception('Oh No!',)
Traceback (most recent call last):
File "asd.py", line 24, in <module>
raise Exception("Oh No!")
Exception: Oh No!
标签:python,weak-references 来源: https://codeday.me/bug/20190701/1344517.html