如何删除实例化对象Python?

时间:2014-02-02 18:43:16

标签: python variables object

我相对较新的面向对象编程,我无法弄清楚如何删除python中的实例化对象。任何帮助将非常感激。

        if self.hit_paddle(pos) == True or self.hit_paddle2(pos) == True:
            bar = bar + 1
        if bar == 1:
            global barbox1
            barbox1 = barfill(canvas)
            barbox1.canvas.move(barbox1.id, 253, 367)
        if bar == 2:
            global barbox2
            barbox2 = barfill(canvas)
            barbox2.canvas.move(barbox2.id, 293, 367)
        if bar == 3:
            global barbox3
            barbox3 = barfill(canvas)
            barbox3.canvas.move(barbox3.id, 333, 367)
        if bar == 4:
            global barbox4
            barbox4 = barfill(canvas)
            barbox4.canvas.move(barbox4.id, 373, 367)
        if bar == 5:
            global barbox5
            barbox5 = barfill(canvas)
            barbox5.canvas.move(barbox5.id, 413, 367)
            bar = 0
            time.sleep(0.2)
            barbox1 = None
            barbox2 = None
            barbox3 = None
            barbox4 = None
            barbox5 = None

这就是代码,我为了删除对象而尝试的主要内容是barbox1 = None,但这似乎没有用。

2 个答案:

答案 0 :(得分:32)

当实例即将被销毁时,将调用

object.__del__(self)

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

除非删除所有引用(由ethan引用)

,否则不会删除对象

另外,来自Python官方文档参考:

  

del x不直接调用x。 del () - 前者减少了   x的引用计数为1,后者仅在x时被调用   引用计数达到零

答案 1 :(得分:9)

delete你是什么意思?在Python中,可以使用del关键字删除引用(或名称),但如果同一对象有其他名称则不会删除该对象。

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

与之相比:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5