Class Variable Access and Assignment

Antoon Pardon apardon at forel.vub.ac.be
Fri Nov 4 06:09:36 EST 2005


Op 2005-11-04, Mike Meyer schreef <mwm at mired.org>:
> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>> Op 2005-11-03, Mike Meyer schreef <mwm at mired.org>:
>>> Antoon Pardon <apardon at forel.vub.ac.be> writes:
>>>>> What would you expect to get if you wrote b.a = b.a + 2?
>>>> I would expect a result consistent with the fact that both times
>>>> b.a would refer to the same object.
>>> Except they *don't*. This happens in any language that resolves
>>> references at run time.
>> Python doesn't resolve references at run time. If it did the following
>> should work.
>
> You left out a key word: "all".
>
>> a = 1
>> def f():
>>   a = a + 1
>>
>> f()
>
> If Python didn't resolve references at run time, the following
> wouldn't work:
>
>>>> def f():
> ...  global a
> ...  a = a + 1
> ... 
>>>> a = 1
>>>> f()
>>>> 

Why do you think so? I see nothing here that couldn't work with
a reference resolved during compile time.

>> But letting that aside. There is still a difference between resolving
>> reference at run time and having the same reference resolved twice
>> with each resolution a different result.
>
> The second is a direct result of the first. The environment can change
> between the references, so they resolve to different results.

No the second is not a direct result of the first. Since there is
only one reference, I see nothing wrong with the environment
remebering the reference and reusing it if it needs the reference
a second time.

Take the code:

  lst[f()] += 1

Now let f be a function with a side effect, that in succession
produces the positive integers starting with one.

What do you think this should be equivallent to:

  t = f()
  lst[t] = lst[t] + 1

or

  lst[f()] = lst[f()] + 1

If you think the environment can change between references then I
suppose you prefer the second approach.

-- 
Antoon Pardon



More information about the Python-list mailing list