still learning python.
In this code, I can reference v0
and v1
to compute v2
inside the Foo
class. So far, so good.
class Foo():
v0="abcd"
v1="efgh"
v2=(v0, v1)
#v3=[(v0, c) for c in v2] # NameError: name 'v0' is not defined.
#v3=[("abcd", c) for c in v2] # Works
print(Foo.v0, Foo.v1, Foo.v2)
#print(Foo.v0, Foo.v1, Foo.v2, Foo.v3)
But if I uncomment the v3=[(v0, c) for c in v2]
line, I get an error that states v0
is not defined.
Traceback (most recent call last):
File "/private/tmp/machin.py", line 1, in <module>
class Foo():
File "/private/tmp/machin.py", line 6, in Foo
v3=[(v0, c) for c in v2]
File "/private/tmp/machin.py", line 6, in <listcomp>
v3=[(v0, c) for c in v2]
NameError: name 'v0' is not defined. Did you mean: '.0'?
Strangely enough, v2
does not receive the same treatment and this line works :
v3=[("abcd", c) for c in v2]
Reading the python doc about classes, scopes and namespaces does not help me to understand what is happening...
So questions :
- Why is the variable
v0
suddenly out of scope butv2
is still reachable ? - Is there a workaround that does not involve retyping the
v0
literal again ? Which one ?