Class Variable Access and Assignment

Antoon Pardon apardon at forel.vub.ac.be
Fri Nov 4 09:35:28 CET 2005


Op 2005-11-03, Magnus Lycka schreef <lycka at carmen.se>:
> Antoon Pardon wrote:
>> Op 2005-11-03, Steven D'Aprano schreef <steve at REMOVETHIScyber.com.au>:
>> 
>> 
>>>>There are two possible fixes, either by prohibiting instance variables
>>>>with the same name as class variables, which would allow any reference
>>>>to an instance of the class assign/read the value of the variable. Or
>>>>to only allow class variables to be accessed via the class name itself.
>>>
>>>There is also a third fix: understand Python's OO model, especially
>>>inheritance, so that normal behaviour no longer surprises you.
>> 
>> 
>> No matter wat the OO model is, I don't think the following code
>> exhibits sane behaviour:
>> 
>> class A:
>>   a = 1
>> 
>> b = A()
>> b.a += 2
>> print b.a
>> print A.a
>> 
>> Which results in
>> 
>> 3
>> 1
>
> On the other hand:
>
> >>> class C:
> ...     a = [1]
> ...
> >>> b=C()
> >>> b.a += [2]
> >>> b.a
> [1, 2]
> >>> C.a
> [1, 2]
>
> I can understand that Guido was a bit reluctant to introduce
> += etc into Python, and it's important to understand that they
> typically behave differently for immutable and mutable objects.

All fine by me. I won't be using python any less because of this,
because I use class variable very little and you can avoid this
problem by avoiding instance that shadow class variables and
always refer to class variables by class name.

But that doesn't mean we should consider this kind of behaviour
as it should be, just because it is in python.

-- 
Antoon Pardon



More information about the Python-list mailing list