Python list should be empty on class instance initialisation, but it's not. Why?
Posted
by
canavanin
on Stack Overflow
See other posts from Stack Overflow
or by canavanin
Published on 2010-12-26T22:25:40Z
Indexed on
2010/12/26
22:54 UTC
Read the original article
Hit count: 223
Hi everyone!
I would like to create instances of a class containing a list that's empty by default; instead of later setting this list to the final full list I would like to successively add items to it. Here's a piece of sample code illustrating this:
#!/usr/bin/python
class test:
def __init__(self, lst=[], intg=0):
self.lista = lst
self.integer = intg
name_dict = {}
counter = 0
for name in ('Anne', 'Leo', 'Suzy'):
counter += 1
name_dict[name] = test()
name_dict[name].integer += 1
name_dict[name].lista.append(counter)
print name, name_dict[name].integer, name_dict[name].lista
When I ran the above program I expected to get
Anne 1 [1]
Leo 1 [2]
Suzy 1 [3]
as I assumed lista
to always be initialised to an empty list.
What I got instead was this:
Anne 1 [1]
Leo 1 [1, 2]
Suzy 1 [1, 2, 3]
If I replace self.lista = lst
by self.lista = []
it works fine, just like when I add the line name_dict[name].lista = []
to the for loop.
Why is it that the contents of the previous objects' lists are retained, yet their values of integer
aren't? I am rather new to Python, so it would be great if someone could point out to me where my thoughts/assumptions have gone astray.
Thanks a lot in advance for your replies.
© Stack Overflow or respective owner