Reputation: 477
class Number():
list = []
number = Number()
number.list.append(0)
print number.list # [0]
newNumber = Number()
newNumber.list.append(1)
print newNumber.list # [0,1]
I have created two instance, why the newNumber.list object has the 0? Why the number and the newNumber use the same list? Anybody can help me? and Why the 'i' is not change in the follow?
class Number:
i = 0
number = Number()
number.i = 1
print number.i # 1
newNumber = Number()
print newNumber.i # 0
Upvotes: 0
Views: 284
Reputation: 39451
That's because you created the list as a member of the class object, rather than the instance objects. If you want to create a seperate list for each instance, you need to do something like this (I changed list
to list_
since it's bad practice to give variables the same name as builtins).
class Number():
def __init__(self):
self.list_ = []
When you access an attribute on an object, it first checks the instance dictionary and then the class object dictionary. That's why making it a member of the class object didn't give you any errors. But since it's only a single list, every object will access that same list.
Upvotes: 11