Python上的类del [英] Python del on classes

查看:226
本文介绍了Python上的类del的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在python中有一个类:

  class A(object):
def __del __ ):
printDel!

__ del __ 任何 A 实例。



可以为类做同样的事吗?我想有一些方法调用时,类本身是垃圾收集,我假设是在脚本出口完成。



先感谢任何指针!






编辑:正如我的预期,每个人都试图驱使我远离使用这种技术(我可能会自己这样的评论:)),虽然问题仍然是:是可能吗?



我想要下面的内容:我有一个类需要清除静态成员。

  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 这样做,但这看起来很丑陋。

解决方案

问题是类包含循环引用回到自己 - 所以当它们被删除时,它们不容易收集 - 因此元类的 __ del __ 方法odf不被调用。



我可以使用Pypy的Python实现来触发它,但不使用cpython - 2.6或3.2。甚至触发,我不得不手动调用垃圾收集器 -
程序退出的Python环境已知是充满了不一致,并且 __ del __

这是我的Pypy会话,其中我触发了调用类 __ del __

 〜] $ pypy 
Python 2.5.2(78826,2010年11月29日,00:18:05)
[PyPy 1.4.0] on linux2
输入help,copyright,credits了解更多信息。
现在对于完全不同的东西:对不起,我会教仙人掌如何
后游
>>>> import gc
>>>>> class Meta(type):
.... def __del __(cls):
.... print(Arghh !!)
....
> >>>> class A(object):
.... __metaclass__ = Meta
....
>>>>> del A
>>>>> gc.collect()
Arghh!
0
>>>>>


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.

解决方案

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                                                                                                                 
>>>>

这篇关于Python上的类del的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆