Nested class doesn't see class scope

Steven D'Aprano steve at pearwood.info
Mon Jul 4 23:20:06 EDT 2016


I got this in Python 3.6:


py> class A:
...     var = 999
...     print(var)  # succeeds
...     class B:
...         x = var
...
999
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in A
  File "<stdin>", line 4, in B
NameError: name 'var' is not defined


I expected that `var` would be available during the construction of B, just
as it was available inside A, but not to methods inside B. Obviously my
expectations are invalid. Can anyone explain the actual behaviour?



-- 
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list