Python del 类

发布于 2024-10-31 12:24:23 字数 759 浏览 1 评论 0原文

假设我们在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

記憶穿過時間隧道 2024-11-07 12:24:24

问题是类包含对其自身的循环引用 - 因此当它们被删除时,它们不容易被收集 - 因此元类的 odf 方法不会被调用。

我可以使用 Pypy 的 Python 实现触发它被调用,但不能使用 cpython - 2.6 或 3.2。即使要触发它,我也必须手动调用垃圾收集器 -
众所周知,程序退出时的 Python 环境充满了不一致,并且在类上存在足够的内部信息以允许 sae 关闭的情况下调用 __del__ 方法的可能性非常小。

这是我的 Pypy 会话,我确实触发了对类的 __del__

 ~]$ pypy                                                                                       
Python 2.5.2 (78826, Nov 29 2010, 00:18:05)                                                                       
[PyPy 1.4.0] on linux2                                                                                            
Type "help", "copyright", "credits" or "license" for more information.                                            
And now for something completely different: ``sorry, I'll teach the cactus how                                    
to swim later''                                                                                                   
>>>> import gc
>>>> class Meta(type):         
....    def __del__(cls):                          
....       print ("Arghh!!")                                              
....                                                                      
>>>> class A(object):                                                                     
....   __metaclass__ = Meta                                                                                     
....                                                                                                                                                                                                                
>>>> del A                                                                                                        
>>>> gc.collect()                                                                                                 
Arghh!!                                                                                                           
0                                                                                                                 
>>>>

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__

 ~]$ pypy                                                                                       
Python 2.5.2 (78826, Nov 29 2010, 00:18:05)                                                                       
[PyPy 1.4.0] on linux2                                                                                            
Type "help", "copyright", "credits" or "license" for more information.                                            
And now for something completely different: ``sorry, I'll teach the cactus how                                    
to swim later''                                                                                                   
>>>> import gc
>>>> class Meta(type):         
....    def __del__(cls):                          
....       print ("Arghh!!")                                              
....                                                                      
>>>> class A(object):                                                                     
....   __metaclass__ = Meta                                                                                     
....                                                                                                                                                                                                                
>>>> del A                                                                                                        
>>>> gc.collect()                                                                                                 
Arghh!!                                                                                                           
0                                                                                                                 
>>>>

2022 - as of Python 3.11 a06, the __del__ method in the metaclass works in cPython, if one calls gc.collect() after deleting all references to the class, just like it happens with pypy on this example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文