0
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
2
  • you must use self.list i think. see this question for self keyword: stackoverflow.com/questions/6990099/… Commented Apr 27, 2013 at 16:15
  • 4
    because list as defined in your code belongs to the class not the instances. you need to write self.list = [] to have one list per instance Commented Apr 27, 2013 at 16:16

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Why is having members with the same name as builtins a problem?
@Eric, then how would you know what number.list means? It could be a plain property which stores some list, but it could also be the list type (constructor), for example I could do number.list('abc').
It doesn't directly cause a problem like it would with local or global variables, but it does make things more confusing.
Why would I ever expect to have a member of my class be the list object? I see no reason to expect a.list to be in any way related to list
class Number: i = 0 number = Number() number.i = 1 print number.i # 1 newNumber = Number() print newNumber.i # 0 why the newNumber.i is not 1?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.