Khi tôi nhập thông tin này vào trình thông dịch, gọi 'y' dường như gọi hàm hủy?Tại sao hàm hủy python được gọi?
class SmartPhone:
def __del__(self):
print "destroyed"
y = SmartPhone()
y #prints destroyed, why is that?
y #object is still there
Đây là một lần chạy, đầu ra không có ý nghĩa với tôi.
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>
>>>
và khác, gọi 'del y' đôi khi gọi destructor và đôi khi không
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
>>>
Không thể trùng lặp. –
Bạn có thể đăng đầu ra thực tế của tập lệnh không? – thegrinner
Bạn có chắc chắn nó in "bị phá hủy" ở dòng này chứ không phải ở cuối tập lệnh không? – Dahaka