Class Variable Access and Assignment

Antoon Pardon apardon at forel.vub.ac.be
Fri Nov 4 05:48:54 EST 2005


Op 2005-11-04, Mike Meyer schreef <mwm at mired.org>:
>
>> Would it be too much to ask that in a line like.
>> 
>>   x = x + 1.
>> 
>> both x's would resolve to the same namespace?
>
> Yes. That's to much bondage for programmers who've become accustomed
> to freedom. Explain why this should be illegal:
>
>>>> class C:
> ...  def __getattr__(self, name):
> ...   x = 1
> ...   return locals()[name]
> ...  def __setattr__(self, name, value):
> ...   globals()[name] = value
> ... 
>>>> o = C()
>>>> o.x = o.x + 1
>>>> x
> 2

I'll answer with a contra question.

Please explain why this is illegal.

x = 1
def f():
  x += 1

f()

IMO your example and mine are essentially the same issue. A name in one
namespace shadowing a name in a different namespace.

So please explain how the same kind of bondage is no problem in the
function but is too much for those who've become accustomed to
freedom in the case of objects with class variables?

-- 
Antoon Pardon



More information about the Python-list mailing list