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

Steven D'Aprano steve at pearwood.info
Thu Sep 20 21:56:46 CEST 2012

On 21/09/12 03:18, eryksun wrote:
> On Thu, Sep 20, 2012 at 12:57 PM, eryksun<eryksun at gmail.com>  wrote:
>> I forgot the obligatory warning about class variables. The subclass
>> gets a shallow copy of the parent class namespace. The in-place
>    ^^^^^^^^^^^^^^^^^^^
>>      >>>  Y.data += [1]
>>      >>>  X.data  # modified parent, too
>>      [1]
>>      >>>  Y.data = Y.data + [2]  # creates new list
> To clarify, it's not an actual dict.copy in the subclass.

Ah, I didn't notice you had corrected yourself before sending my
own correction.

> In fact, the
> atrribute is initially only in the parent __dict__, where it's found
> by object.__getattribute__. In the 2nd example, Y.data on the
> right-hand side is actually found in the parent class X, then the
> expression creates a new list which is stored back to Y.

Pretty much.

Inheritance couldn't work correctly if subclasses made copies of their
parent namespaces.


More information about the Tutor mailing list