0

i just have a puzzling question abou class attributes in python. consider the following class below:

class A:
    __lst = []
    def add(self, str):
        self.__lst.append(str)
        print len(self.__lst)

i tried to make two instances x and y and i got this:

>>> x = A()
>>> x.add('aaa')
1
>>> x.add('bbb')
2
>>> y = A()
>>> y.add('aaa')
3
>>> y.add('bbb')
4

i was expecting that the instance of y will have a separate copy of the list attribute but it seems that the list just gets bigger even if you use another object to add elements to the list. it's simply weird.

can anybody please enlighten me on this matter? thanks a lot in advance for your help. :-)

rbolante
  • 53
  • 1
  • 2
  • 2
    "I was expecting that the instance of y will have a separate copy of the list attribute" - why would you expect this? It's a class attribute (a concept you seem to know of since you use the term), of course it belongs to the class, not the instance. – millimoose May 15 '13 at 16:56
  • 1
    Probably because Python isn't just java with different syntax – John La Rooy May 15 '13 at 17:00
  • Sorry i was referring to the attribute itself which means that the list attribute of instance x has nothing to do with the list attribute of instance y. – rbolante May 16 '13 at 04:26

2 Answers2

1

If you define an attribute inside of the class body then it will be a class attribute, and it will be shared by all instances. In your code self.__lst is going to be a reference to A.__lst.

To have a separate list for each attribute, define it as self.__lst inside of the __init__() function:

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

    def add(self, s):
        self.__lst.append(s)
        print len(self.__lst)

In addition to the change referenced above, I also made some minor modifications so that your code follows some Python best practices: inheriting from object (new-style class) and not using str (or any other built-in name) as a variable name.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

Variables declared inside a class but not by means of self are class-level properties (like your __lst). They are equivalent to Java's static. If you want your property to be unique for all instances, you need to declare them via self (i.e., self.__lst).

skytreader
  • 11,467
  • 7
  • 43
  • 61