1

I would like to know what are the rules for class variable assignment in the case that the it references something outside of the class definition.

The following is probably a more concrete version of my question.

Why do I get an error here?

>>> def foo():
...   x = 123
...   class A:
...     x = x
...   return A
... 
>>> A = foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in foo
  File "<stdin>", line 4, in A
NameError: name 'x' is not defined

But the following two are OK?

>>> x = 123
>>> class A:
...   x = x
... 
>>> A.x
123
>>> 
>>> def foo():
...   x = 123
...   class A:
...     y = x
...   return A
... 
>>> A = foo()
>>> A.y
123

I'm using Python 3.7.0.

0 Answers0