[Tutor] Python __del__ method

Peter Otten __peter__ at web.de
Wed Jul 12 03:08:02 EDT 2017


eryk sun 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.

Or remove it explicitly:

>>> x = Robot("Foo")
Foo has been created!
>>> x
<__main__.Robot object at 0x7fe839ab77f0>
>>> del x
>>> import builtins
>>> del builtins._
Robot has been destroyed




More information about the Tutor mailing list