Class Variable Access and Assignment

Antoon Pardon apardon at forel.vub.ac.be
Fri Nov 4 14:32:03 CET 2005


Op 2005-11-04, Magnus Lycka schreef <lycka at carmen.se>:
> 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.

I meant those 'x' do be any general expression
that refers to an object. Like

  a.b[c.f] = a.b[c.f] + 1

> 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 issue is with c.x += 1

Sure I find the fact that the same reference two
times in the same line can reference variable
in two different namespaces ugly.

But that one single reference refers to two
variables in two different namespaces that is
IMO more than ugly.

Suppose I have the following:

class I:
  def __init__(self):
    self.v = 0
  def __call__(self):
    t = self.v
    self.v += 1
    return t

i = I()
lst = range(10)
lst[i()] += 20

Nobody seems to find that this should be treated
exactly the same as
lst[i()] = lst[i()] + 20

People seem to think since lst[i()] only occurs
once, it should be only refering to one entity.

Well I think the same kind of reasoning can apply
to 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.

But there is no reason that two dot-operator are
executed when only one dot-operator is in the text.

Just as there is no reason that two i() calls
should be made when only one call is in the text.

> 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...

Well I thought in python explicit was better than
implicit.

-- 
Antoon Pardon



More information about the Python-list mailing list