Class Variable Access and Assignment

Magnus Lycka lycka at carmen.se
Fri Nov 4 07:46:01 EST 2005


Antoon Pardon wrote:
> Would it be too much to ask that in a line like.
> 
>   x = x + 1.
> 
> both x's would resolve to the same namespace?

They always do Antoon. There is no such issue for
local (or global) varibles. The issue has to do
with c.x = c.x + 1. In this case it's clearly
designed and documented that this corresponds to:

setattr(c, 'x', getattr(c, 'x') + 1)

The result of these operations depends on e.g.
how the __setattr__ and __getattr__ methods in
the class in question are defined.

You need to understand that the dot-operaterator
always involves a lookup-operation that can be
implemented in various ways.

It's well defined that you can do things like:

 >>> class Counter:
...     c=0
...     def __call__(self):
...         self.c+=1
...     def __str__(self):
...         return str(self.c)
...
 >>> c=Counter()
 >>> c()
 >>> print c
1
 >>> c()
 >>> print c
2
 >>> class C5(Counter):
...     c=5
...
 >>> c5=C5()
 >>> c5()
 >>> print c5
6

Of course, you could design a language, say Pythoon
or Parthon, where this is illegal, and you force the
programmer to do something longer such as:

 >>> class APCounter:
...     c=0
...     def __init__(self):
...         self.c = self.__class__.c
...     def __call__(self):
...         self.c+=1
...     def __str__(self):
...         return str(self.c)
...

I don't see this as an improvement though...



More information about the Python-list mailing list