Class Variable Access and Assignment
Stefan Arentz
stefan.arentz at gmail.com
Thu Nov 3 09:35:50 EST 2005
Antoon Pardon <apardon at forel.vub.ac.be> writes:
...
> Fine, we have the code:
>
> b.a += 2
>
> We found the class variable, because there is no instance variable,
> then why is the class variable not incremented by two now?
Because it really is executed as:
b.a = b.a + 2
1. get 't'b.a and store it in a temporary 't' (found the instance)
2. add 2 to 't'
3. store 't' in 'b.a'
The last operation stores it into an instance variable.
>
> > Remember, Python is a dynamic language.
>
> So? Python being a dynamic language doesn't prevent the following to fail:
>
> >>> a=1
> >>> def f():
> ... a += 2
> ...
> >>> f()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 2, in f
> UnboundLocalError: local variable 'a' referenced before assignment
See the 'global' keyword.
s.
More information about the Python-list
mailing list