A nested class is not defined on its own

The following code successfully prints OK :

 class B(object): def __init__(self): super(B, self).__init__() print 'OK' class A(object): def __init__(self): self.B() B = B A() 

but the following, which should work the same as above, raises a NameError: global name 'B' is not defined

 class A(object): def __init__(self): self.B() class B(object): def __init__(self): super(B, self).__init__() print 'OK' A() 

why?

+4
source share
1 answer

B is available in area A - use AB :

 class A(object): def __init__(self): self.B() class B(object): def __init__(self): super(AB, self).__init__() print 'OK' A() 

See the Python Scopes and Namespaces documentation.

+2
source

Source: https://habr.com/ru/post/1498055/


All Articles