class attribute confusion
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Dec 4 09:34:38 EST 2010
On Sat, 04 Dec 2010 15:00:43 +0100, Omar Abo-Namous wrote:
>>> I think this behaviour is totally wrong, since it seems
>>> A.__init__(self) is changing the value inside of A() not inside of the
>>> object variable 'self' (that should be x or y)!!
>> It's not wrong at all. You expect "mylist" to behave as an instance
>> attribute, but you defined it as a class attribute. Instance
>> attributes are naturally initialised in the __init__() method.
>>
> Could you please point me to a reference in the doc??
http://docs.python.org/reference/datamodel.html
In the section about classes:
"Class attribute assignments update the class’s dictionary ..."
and in the section about class instances:
"Attribute assignments and deletions update the instance’s dictionary,
never a class’s dictionary."
In this specific example, you also have to realise that mylist.append()
mutates the list in place, and doesn't create a new list. It doesn't
matter whether the list comes from a global variable, a local variable,
an instance attribute or a class attribute, append is always an inplace
operation.
--
Steven
More information about the Python-list
mailing list