14

I am new to python recently. Previously all my programming knowledge are limited on Java. So here I have a question about object variables in Python. I know that object variables in Python share on class instances. For example.

class A:
    list=[]

y=A()
x=A()

x.list.append(1)
y.list.append(2)
x.list.append(3)
y.list.append(4)

print x.list
    [1,2,3,4]
print y.list
    [1,2,3,4]

So my questions is that how many memory copies does A.list have? only 1 or just as many as number of instances? object variables in python sharing behavior is just like Java's static class variables, are these two concepts same or different? if different, what's diff between them?

JoJo
  • 1,377
  • 3
  • 14
  • 28

1 Answers1

3

In python, anything declared at the class scope is effectively global. When you look up that attribute on an instance, python doesn't find it, so it then looks on the class (then it continues looking on the base classes all the way up the method resolution order). So, in your case, x.list is the exact same thing as A.list because there is no instance attribute list attached to x. Similary, y.list is the same as A.list so x.list and y.list refer to the same underlying list. (Phew!)

As I understand it, this is at least similar to Java's static (though I'm not fluent enough in Java to say exactly how similar).

The typical way to disassociate an attribute from the class is to bind that attribute to an instance (usually in __init__):

class A(object):
    def __init__(self):
        self.list = []

In the above example, self is the instance and it gets passed (implicitly) to any 'normal' method (including "magic" methods like __init__).

Now if you do your experiment again, you'll see that x.list takes the value of [1, 3] and y.list is now [2, 4].


Now the test. What happens if you do your experiment on this class?

class A(object):
    list = []
    def __init__(self):
        self.list = []

Answer: x.list = [1, 3] and y.list = [2, 4]. The reason is because when python does x.list, it looks on the instance first (before looking at the class). Since an attribute with the name list is found on the instance, that is the one that is used.

mgilson
  • 300,191
  • 65
  • 633
  • 696