Class Variable Access and Assignment

Eric Nieuwland eric.nieuwland at xs4all.nl
Thu Nov 3 11:55:54 EST 2005


Steven D'Aprano wrote:
> On Thu, 03 Nov 2005 15:13:52 +0100, Eric Nieuwland wrote:
>> 2 When an instance of the class is created, what effectively happens 
>> is
>> that a shallow copy of the class object is made.
>> 	Simple values and object references are copied.
>
> No.
>
> py> class Parrot:
> ...     var = 0
> ...
> py> p = Parrot()
> py> Parrot.var is p.var
> True
> py> Parrot.var = {"Hello world": [0, 1, 2]}
> py> Parrot.var is p.var
> True
>
> It all boils down to inheritance. When Python does a look up of an
> attribute, it looks for an instance attribute first (effectively trying
> instance.__dict__['name']). If that fails, it looks up the class second
> with instance.__class__.__dict__['name'], and if that fails it goes 
> into a
> more complex search path looking up any superclasses (if any).

Note my use of "effectively" and "shallow copy". Your example 
demonstrates how Python postpones the shallow copy until you tell the 
object to differ from the class/

The examples used only use a class an an instance thereof. They are 
valid without inheritance.

>> This explains:
>> - why methods and complex objects (e.g. lists) are shared among
>> instances of a class and the class itself
>> - simple values are not shared
>
> No. it is all about the inheritance, and mutable/immutable objects.

NO. You're referring to the implemented mechanism. Other 
implementations with the same semantics are possible.




More information about the Python-list mailing list