Python instances and attributes: is this a bug or i got it totally wrong?
Posted
by Mirko Rossini
on Stack Overflow
See other posts from Stack Overflow
or by Mirko Rossini
Published on 2010-03-08T16:37:56Z
Indexed on
2010/03/08
16:51 UTC
Read the original article
Hit count: 242
Suppose you have something like this:
class intlist:
def __init__(self,l = []):
self.l = l
def add(self,a):
self.l.append(a)
def appender(a):
obj = intlist()
obj.add(a)
print obj.l
if __name__ == "__main__":
for i in range(5):
appender(i)
A function creates an instance of intlist and calls on this fresh instance the method append on the instance attribute l.
How comes the output of this code is:
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
? If i switch
obj = intlist()
with
obj = intlist(l=[])
I get the desired output
[0]
[1]
[2]
[3]
[4]
Why this happens?
Thanks
© Stack Overflow or respective owner