5

当我在解释器中输入这个时,调用'y'似乎调用了析构函数?

class SmartPhone:
    def __del__(self):
       print "destroyed"

y = SmartPhone()
y  #prints destroyed, why is that?
y  #object is still there

这是一次运行,输出对我来说没有意义。

C:\Users\z4>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> class SmartPhone:
...     def __del__(self):
...        print "destroyed"
...
>>> y = SmartPhone()
>>> del y
destroyed
>>> y = SmartPhone()
>>> y
<__main__.SmartPhone instance at 0x01A7CBC0>
>>> y
<__main__.SmartPhone instance at 0x01A7CBC0>
>>> y
<__main__.SmartPhone instance at 0x01A7CBC0>
>>> del y
>>> y = SmartPhone()
>>> y
destroyed
<__main__.SmartPhone instance at 0x01A7CB98>
>>>

另一个,调用 'del y' 有时会调用析构函数,有时不会

C:\Users\z4>python
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> class SmartPhone:
...     def __del__(self):
...             print "destroyed"
...
>>>
>>> y = SmartPhone()
>>>
>>> y
<__main__.SmartPhone instance at 0x01B6CBE8>
>>> y
<__main__.SmartPhone instance at 0x01B6CBE8>
>>> y
<__main__.SmartPhone instance at 0x01B6CBE8>
>>> del y
>>> y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> y = SmartPhone()
>>> y
destroyed
<__main__.SmartPhone instance at 0x01B6CC38>
>>> del y
>>> y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>>
4

5 回答 5

15

有问题的输出仅在交互式 shell 中复制。

在交互式会话中,_存在附加变量,它引用最后一个值。

使用sys.getrefcount检查引用计数:

>>> import sys
>>> class SmartPhone:
...     def __del__(self):
...        print "destroyed"
...
>>> y = SmartPhone()
>>> sys.getrefcount(y) # not printed, _ does not reference SmartPhone object yet.
2
>>> y
<__main__.SmartPhone instance at 0x000000000263B588>
>>> sys.getrefcount(y) # y printed, _ reference SmartPhone object.
3

2,3在上面的输出中应该是1, 2。它们以这种方式打印,因为 getrefcount() 会临时增加引用计数,如 getrefcount 文档中所述。


我如下更改了 SmartPhone,以便于检查发生了什么。

>>> class SmartPhone(object):
...     def __init__(self, name):
...         self.name = name
...     def __repr__(self):
...         return super(SmartPhone, self).__repr__() + ' name=' + self.name
...     def __del__(self):
...        print "destroyed", self
...
>>> y = SmartPhone('first')
>>> del y # deleted immediately, because only "y" reference it.
destroyed <__main__.SmartPhone object at 0x00000000024FEFD0> name=first
>>> y = SmartPhone('second')
>>> y # at this time, _ reference to second y (y's reference count is now 2)
<__main__.SmartPhone object at 0x00000000024FEFD0> name=second
>>> y
<__main__.SmartPhone object at 0x00000000024FEFD0> name=second
>>> y
<__main__.SmartPhone object at 0x00000000024FEFD0> name=second
>>> del y # not deleted immediately, because _ reference it.
>>> y = SmartPhone('third') # _ still reference the second y, because nothing is printed.
>>> y # second y is deleted, because _ now reference the third y. (no reference to the second y)
destroyed <__main__.SmartPhone object at 0x00000000024FEFD0> name=second
<__main__.SmartPhone object at 0x000000000264A470> name=third
于 2013-07-10T15:21:14.657 回答
6

您必须y在同一个解释器会话中重置 的值,将原始对象的引用计数降至 0。然后,由于第一个对象没有被引用,它被销毁,但新对象被引用y

>>> class SmartPhone:
...   def __del__(self):
...     print 'destroyed'
...
>>> y = SmartPhone()
>>> y
<__main__.SmartPhone instance at 0x00000000021A5608>
>>> y = SmartPhone()
>>> y
destroyed
<__main__.SmartPhone instance at 0x00000000021A5648>

请注意,这两个对象的地址是不同的。打印的destroyed是 when__del__在第一个实例上调用时0x00000000021A5608

在您的示例中,当您显式调用del对象引用时,它可能会立即被销毁(如果这是对该对象的唯一引用并且 GC 立即找到它)。当您这样做时y = SmartPhone(),旧对象可能不会立即被销毁,但会在收集器找到它并看到引用计数为 0 时被销毁。这通常几乎立即发生,但可以延迟。

print 'destroyed'可能会立即显示,也可能会在会话中执行 1 个或多个附加命令后显示,但应该会很快发生。

于 2013-07-10T15:11:58.950 回答
0

扩展@falsetru 的答案,这是一款智能手机,可以轻松查看正在发生的事情。

myid = 0

class SmartPhone(object):
    def __init__(self):
        global myid
        self.myid = myid
        print("init %d" % self.myid)
        myid += 1
    def __del__(self):
        print("delete", self)
    def __repr__(self):
        return "repr %d" % self.myid
    def __str__(self):
        return "str %d" % self.myid

>>> 
>>> y=SmartPhone()
init 0
>>> # _ will hold a ref to y
... 
>>> 
>>> y
repr 0
>>> _
repr 0
>>> # del only decreases the ref count
... 
>>> del y
>>> _
repr 0
>>> # _ still refs 0
... 
>>> y=SmartPhone()
init 1
>>> # but now i reassign _ and 0 goes away
... 
>>> y
delete str 0
repr 1
>>> 
于 2013-07-10T16:04:30.313 回答
0

__del__不是 C++ 意义上的析构函数。它是一种保证在对象销毁之前和对象能够被垃圾回收之后运行的方法。

在 CPython 中,当引用计数达到 0 时会发生这种情况。因此,如果您将值重新分配给包含具有__del__方法的对象的单个变量,则该对象的该方法将在此后不久被调用。

于 2013-07-10T15:20:11.797 回答
0

我运行了相同的代码,但得到了不同的结果:

class SmartPhone:
    def __del__(self):
       print "destroyed"

y = SmartPhone()
del y
print y  #prints destroyed, why is that?

输出 :

>>> 
destroyed

Traceback (most recent call last):
  File "C:/Users/Kulanjith/Desktop/rand.py", line 7, in <module>
    print y  #prints destroyed, why is that?
NameError: name 'y' is not defined

实际上del y做了它的工作,但你代替

>>> y = SmartPhone() # create object
>>> del y # delete's the object y, therefore no variable exist after this line executes
destroyed
>>> y = SmartPhone() # again creates a object as a new variable y
>>> y # since no __repr__ methods are define the outcome is normal
<__main__.SmartPhone instance at 0x01A7CBC0>
于 2013-07-10T15:18:45.163 回答