Class Variable Access and Assignment
Bengt Richter
bokr at oz.net
Sat Nov 5 03:11:51 CET 2005
On 4 Nov 2005 11:09:36 GMT, Antoon Pardon <apardon at forel.vub.ac.be> wrote:
[...]
>
>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.
>
I am quite sympathetic to your probe of python semantics, but I
don't think the above is an argument that should be translated
to attribute assignment. BTW, ISTM that augassign (+=) is
a red herring here, since it's easy to make a shared class variable
that is augassigned apparently as you want, e.g.,
>>> class shared(object):
... def __init__(self, v=0): self.v=v
... def __get__(self, *any): return self.v
... def __set__(self, _, v): self.v = v
...
>>> class B(object):
... a = shared(1)
...
>>> b=B()
>>> b.a
1
>>> B.a
1
>>> b.a += 2
>>> b.a
3
>>> B.a
3
>>> vars(b)
{}
>>> vars(b)['a'] = 'instance attr'
>>> vars(b)
{'a': 'instance attr'}
>>> b.a
3
>>> b.a += 100
>>> b.a
103
>>> B.a
103
>>> B.a = 'this could be prevented'
>>> b.a
'instance attr'
>>> B.a
'this could be prevented'
The spelled out attribute update works too
>>> B.a = shared('alpha')
>>> b.a
'alpha'
>>> b.a = b.a + ' beta'
>>> b.a
'alpha beta'
>>> B.a
'alpha beta'
But the instance attribute we forced is still there
>>> vars(b)
{'a': 'instance attr'}
You could have shared define __add__ and __iadd__ and __radd__ also,
for confusion to taste ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list