在嵌套类中使用 super() [英] Using super() in nested classes

查看:45
本文介绍了在嵌套类中使用 super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下:

A 类(对象):B类(对象):def __init__(self):super(B, self).__init__()

这会产生一个错误:

<前>NameError: 全局名称 B 未定义.

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

更新:

我发现了问题.

我曾经上过这样一堂课:

A 类(对象):B类(对象):def __init__(self):super(B, self).__init__()某个属性 = B()

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

解决方案

我不知道为什么 A.B 不能正常工作,因为它应该......这是一些有效的 shell 输出:

<预><代码>>>>A类(对象):... B类(对象):... def __init__(self):... super(A.B, self).__init__()... def getB(self):...返回 A.B()...>>>A().getB()<__main__.B 对象在 0x100496410>

Imagine this:

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

This creates an error:

NameError: global name B is not defined.

I've tried A.B, but then it says that A is not defined.

Update:

I've found the problem.

I've had a class like this:

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

    someattribute = B()

In that scope, A isn't defined yet.

解决方案

I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:

>>> 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>

这篇关于在嵌套类中使用 super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆