Reputation: 11
Why is this not working as expected (at least for me)? I can't figure why.
class Fred:
def __init__(self):
self.a=0
fred=Fred()
lista=[]
for i in range(5):
fred.a=i
lista.append(fred)
for i in lista:
print(str(i.a))
All I get is 5 times the number 4 and not from 0 to 4. Any comments? Thanks
Upvotes: 1
Views: 114
Reputation: 129011
You've got one Fred
instance and keep adding that one instance to the list, changing its a
property while you do that. Adding to the list does not copy the Fred
object; it just adds another reference to the same object. You can get your expected behavior by creating a new Fred
inside each iteration of the loop.
Upvotes: 0
Reputation: 137
What is happening is that the reference to Fred is being overwritten each time you loop in the for i in range(5)
. If you move the fred=Fred()
inside that loop and create a new object each time, then you should see the expected result.
Upvotes: 1