Class Variable Access and Assignment

Christopher Subich csubich.spam.block at spam.subich.block.com
Fri Nov 4 15:22:51 CET 2005


Antoon Pardon wrote:
> Op 2005-11-03, Stefan Arentz schreef <stefan.arentz at gmail.com>:
>>The model makes sense in my opinion. If you don't like it then there are
>>plenty of other languages to choose from that have decided to implement
>>things differently.
> 
> 
> And again this argument. Like it or leave it, as if one can't in general
> like the language, without being blind for a number of shortcomings.
> 
> It is this kind of recations that make me think a number of people is
> blindly devoted to the language to the point that any criticism of
> the language becomes intollerable.

No, it's just that a goodly number of people actually -like- the 
relatively simple conceputal model of Python.

Why /shouldn't/

 >>>a.x = foo

correspond exactly to

 >>>setattr(a,'x',foo) #?

Similarly, why shouldn't

 >>>foo = a.x

correspond exactly to

 >>>foo = getattr(a,'x') #?

With that in mind, the logical action for

 >>>a.x = f(a.x)

is

 >>>setattr(a,'x',f(a,'x')) #,

and since

 >>>a.x += foo

is equal to

 >>>a.x = A.__iadd__(a.x,foo) # (at least for new-style classes
 >>> # that have __iadd__ defined.  Otherwise, it falls back on
 >>> # __add__(self,other) to return a new object, making this
 >>> # evern more clear),

why shouldn't this translate into

 >>>setattr(a,'x',A.__iadd__(getattr(a,'x'),foo)) #?

Looking at it this way, it's obvious that the setattr and getattr may do 
different things, if the programmer understands that "instances (can) 
look up object attributes, and (always) set instance attributes."  In 
fact, it is always the case (so far as I can quickly check) that += ends 
up setting an instance attribute.  Consider this code:

 >>> class foo:
 >>>   x = [5]
 >>> a = foo()
 >>> a += [6]
 >>> a.x
[5,6]
 >>> foo.x
[5,6]
 >>> foo.x = [7]
 >>> a.x
[5,6]

In truth, this all does make perfect sense -- if you consider class 
variables mostly good for "setting defaults" on instances.



More information about the Python-list mailing list