在嵌套类中使用super()

Geo*_*lly 23 python super

想象一下:

class A(object):
    class B(object):
        def __init__(self):
            super(B, self).__init__()
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

NameError: global name B is not defined.

我试过了A.B,但后来说它A没有定义.

更新:

我发现了这个问题.

我有一个这样的课:

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

    someattribute = B()
Run Code Online (Sandbox Code Playgroud)

在该范围内,A尚未定义.

Dou*_*yle 18

我不确定为什么AB不适合你,因为它应该..这是一些有效的shell输出:

>>> class A(object):
...   class B(object):
...     def __init__(self):
...       super(A.B, self).__init__()
...   def getB(self):
...     return A.B()
... 
>>> A().getB()
<__main__.B object at 0x100496410>
Run Code Online (Sandbox Code Playgroud)


Cor*_*sky 5

由于B可能永远不会自我扩展,这应该工作:

class A(object):
    class B(object):
        def __init__(self):
            super(self.__class__, self).__init__()
Run Code Online (Sandbox Code Playgroud)