Python del 类
假设我们在 python 中有一个类:
class A(object):
def __del__(self):
print "Del!"
在删除/垃圾收集任何 A
实例时调用 __del__
。
是否可以对班级做同样的事情?我希望在类本身被垃圾收集时调用一些方法,我假设这是在脚本退出时完成的。
预先感谢您的任何指点!
编辑:正如我所预料的那样,每个人都试图阻止我使用这种技术(我自己可能会做出这样的评论:)),尽管问题仍然存在:这可能吗?
我想要以下内容:我有一个带有需要清理的静态成员的类。
class A(object):
class Meta(type):
def __new__(mcs, name, bases, attrs):
attrs['conn'] = sqlite3.connect( DB_FILE )
return type.__new__(mcs, name, bases, attrs)
__metaclass__ = Meta
我希望在程序关闭之前调用 A.conn.close()
,即当我知道不会再创建 A
的实例时。我知道我可以使用 atexit
来做到这一点,但这看起来非常难看。
Lets assume we have a class in python:
class A(object):
def __del__(self):
print "Del!"
__del__
is called upon deleting/garbage collection of any A
instance.
Is is possible to do the same for a class? I would like to have some method called when the class itself is garbage collected, which I assume is being done at the script exit.
Thanks in advance for any pointers!
Edit: Just as I have expected, everyone is trying to drive me away from using this technique (I would probably make such a comment myself:)), though the question still stands: is it possible?
I want to the the following: I have a class with a static member that needs to be cleaned.
class A(object):
class Meta(type):
def __new__(mcs, name, bases, attrs):
attrs['conn'] = sqlite3.connect( DB_FILE )
return type.__new__(mcs, name, bases, attrs)
__metaclass__ = Meta
I would like A.conn.close()
to be called, but just before the program closes - i.e. when I know that no more instances of A
will be ever created. I know I can do this with atexit
, but this just seems very ugly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是类包含对其自身的循环引用 - 因此当它们被删除时,它们不容易被收集 - 因此元类的 odf 方法不会被调用。
我可以使用 Pypy 的 Python 实现触发它被调用,但不能使用 cpython - 2.6 或 3.2。即使要触发它,我也必须手动调用垃圾收集器 -
众所周知,程序退出时的 Python 环境充满了不一致,并且在类上存在足够的内部信息以允许 sae 关闭的情况下调用 __del__ 方法的可能性非常小。
这是我的 Pypy 会话,我确实触发了对类的
__del__
2022 的调用 - 从 Python 3.11 a06 开始,
__del__
方法元类在 cPython 中工作,如果在删除对该类的所有引用后调用 gc.collect() ,就像本例中 pypy 发生的情况一样。The problem is that classes contain circular references back to themselves - so when they are deleted they are not easily collected - thus the
__del__
method odf the metaclass is not called.I could trigger it being called using Pypy's Python implementation, but not using cpython - either 2.6 or 3.2. And even to trigger that, I had to manually invoke the garbage collector -
The Python environment at program exit is known to be full of inconsitencies, and the chances of the
__del__
method being called while enough internal information on the class would exist to allow a sae shut down would be very slim.Here is my Pypy session where I did trigger the call to the class'
__del__
2022 - as of Python 3.11 a06, the
__del__
method in the metaclass works in cPython, if one callsgc.collect()
after deleting all references to the class, just like it happens with pypy on this example.