Nested class doesn't see class scope

Rustom Mody rustompmody at gmail.com
Mon Jul 4 23:37:49 EDT 2016


On Tuesday, July 5, 2016 at 8:50:57 AM UTC+5:30, Steven D'Aprano wrote:
> 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?
> 

Heh!
Nice to see you confused by python's ‘concave’ LEGB rule
One of those thing I never get used to…



More information about the Python-list mailing list