[Python] python class attributes: unexpected behaviour [duplicate]

Discussão em 'Python' iniciado por Stack, Setembro 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am puzzled about class attributes in Python. Consider the following class:

    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 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.

    Can anybody please enlighten me on this matter?

    Continue reading...

Compartilhe esta Página