[Tutor] Populating a list with object to be called by a class

eryksun eryksun at gmail.com
Thu Sep 20 18:57:57 CEST 2012


On Thu, Sep 20, 2012 at 12:25 PM, eryksun <eryksun at gmail.com> wrote:
>
>             cls._count += 1

I forgot the obligatory warning about class variables. The subclass
gets a shallow copy of the parent class namespace. The in-place
addition above works because numbers are immutable. However, an
in-place operation on a mutable object would modify the value shared
by the parent and all other subclasses.

Simple example:

    >>> class X(object): data = []
    >>> class Y(X): pass
    >>> Y.data += [1]
    >>> X.data  # modified parent, too
    [1]

But rebinding the attribute name is OK:

    >>> Y.data = Y.data + [2]  # creates new list
    >>> Y.data
    [1, 2]
    >>> X.data
    [1]


More information about the Tutor mailing list