Issue
Given the following code:
class wat():
def __init__(self):
self.ok = "ok"
print "hi"
def __del__(self):
print "bye"
i = [1,2,3,4]
for thing in i:
print thing
hey = wat()
I get the following ouput:
1
hi
2
hi
bye
3
hi
bye
4
hi
bye
bye
It appears that the objects created in one iteration don't get destroyed until after the object in the next iteration gets created. Is this what is actually going on, and if so, why does it do that? I was always under the assumption that once the iteration is complete, then all variables and objects die (unless something else is referencing those objects).
Solution
This is normal. Each time you run through the hey = wat()
line, a new object is created (you get the 'hi') and then it replaces the old one that was in hey
. The old one is then destroyed, because there is nothing referring to it. (note, as explained in the Python documentation for the Assignment Statements, first the right-side expression is evaluated and only then the result is bound to the variable on the left side (hence, you get first a hi
from the execution of wat()
and only then bye
.
Obviously, on the first iteration, hey
isn't defined, so you got only hi
after the 1
line.
Answered By - Leo K
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.