gpt4 book ai didi

Python weakref 回调和 __del__ 执行顺序

转载 作者:太空宇宙 更新时间:2023-11-03 11:11:42 26 4
gpt4 key购买 nike

在 Python 中,有没有办法在对象完成后调用函数?

我认为 weakref 中的回调会执行此操作,但似乎一旦对象被垃圾回收,但在调用对象 __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 weakref 回调和 __del__ 执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1228791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com