嵌套类本身未定义

问题描述:

以下代码成功打印OK:

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

class A(object):
    def __init__(self):
       self.B()

    B = B

A()

,但以下应该与上面的工作原理相同的内容引发了NameError: global name 'B' is not defined

but the following which should work just as same as above one raises 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()

为什么?

BA类的范围内可用-请使用A.B:

B is available in the scope of A class - use A.B:

class A(object):
    def __init__(self):
       self.B()

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

A()

请参阅有关 Python作用域和命名空间的文档.