Class Variable Access and Assignment

Bengt Richter bokr at oz.net
Thu Nov 3 21:53:33 EST 2005


On 3 Nov 2005 12:20:35 GMT, Antoon Pardon <apardon at forel.vub.ac.be> wrote:

>Op 2005-11-03, Stefan Arentz schreef <stefan.arentz at gmail.com>:
>> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>>
>>> 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
>>
>> I find it confusing at first, but I do understand what happens :-)
>
>I understand what happens too, that doesn't make it sane behaviour.
>
>> But really, what should be done different here?
>
>I don't care what should be different. But a line with only one
>referent to an object in it, shouldn't be referring to two different
>objects.
>
>In the line: b.a += 2, the b.a should be refering to the class variable
>or the object variable but not both. So either it could raise an
>attribute error or add two to the class variable.
>
>Sure one could object to those sematics too, but IMO they are preferable
>to what we have now.
>
A somewhat similar name space problem, where you could argue
that "a"  prior to += should be seen as defined in the outer scope,
but lookahead determines that a is local to inner, period, so that
is the reference that is used (and fails).

 >>> def outer():
 ...     a = 1
 ...     def inner():
 ...         a += 2
 ...         print a
 ...     print 'outer a', a
 ...     inner()
 ...     print 'outer a', a
 ...
 >>> outer()
 outer a 1
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 7, in outer
   File "<stdin>", line 4, in inner
 UnboundLocalError: local variable 'a' referenced before assignment

Regards,
Bengt Richter



More information about the Python-list mailing list