[Tutor] Python __del__ method

boB Stepp robertvstepp at gmail.com
Tue Jul 11 20:20:55 EDT 2017


On Tue, Jul 11, 2017 at 7:13 PM, eryk sun <eryksun at gmail.com> wrote:
> On Wed, Jul 12, 2017 at 12:07 AM, eryk sun <eryksun at gmail.com> wrote:
>> On Tue, Jul 11, 2017 at 2:47 PM, Jia Yue Kee <JiaYue.Kee at firstsolar.com> wrote:
>>>
>>> Case 2: If I were to run the code in "Interactive Mode", the following output will be obtained:
>>>
>>>>>> x = Robot("Tik-Tok")
>>> Tik-Tok has been created!
>>>>>> y = Robot("Jenkins")
>>> Jenkins has been created!
>>>>>> z = x
>>>>>> z
>>> <__main__.Robot object at 0x02D7E910>
>>>>>> x
>>> <__main__.Robot object at 0x02D7E910>
>>>>>> del x
>>>>>> del z
>>>>>> del y
>>> Robot has been destroyed
>>>
>>> My question being why is that "Robot has been destroyed" is only printed once in Case 2
>>> (interactive mode) while it is printed out twice in Case 1 (script mode)?
>>
>> The REPL (interactive mode) keeps a reference to the last non-None
>> result as builtins `_`, for convenient access to the last result. In
>> your case, it results from evaluating `x`. Thus you have a hidden
>> reference that's keeping that object alive. Enter anything except None
>> or _ to clear that reference.
>
> Well, not just any statement. It has to evaluate to another object
> except None or the Robot object that _ currently references. For
> example, enter 42.

I found the OP's question and Eryk's answer of interest, too.  To make
it easier for me to understand what was going on I modified the OP's
code slightly so I could see which instance's __del__ method was being
called and got the following:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64
bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
py3: class Robot:
...     def __init__(self, name):
...             self.name = name
...             print(self.name, "has been created!")
...     def __del__(self):
...             print(self.name, "has been destroyed!")
...
py3: x = Robot("Tik-Tok")
Tik-Tok has been created!
py3: y = Robot("Jenkins")
Jenkins has been created!
py3: z = x
py3: z
<__main__.Robot object at 0x0000000002002160>
py3: x
<__main__.Robot object at 0x0000000002002160>
py3: del x
py3: del z
py3: del y
Jenkins has been destroyed!
py3: x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
py3: z
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'z' is not defined
py3: _
<__main__.Robot object at 0x0000000002002160>
py3: x = 1
py3: _
<__main__.Robot object at 0x0000000002002160>
py3: x
Tik-Tok has been destroyed!
1



-- 
boB


More information about the Tutor mailing list