在嵌套类中使用 super()
想象一下:
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
这会产生一个错误:
NameError: global name B is not defined.
我尝试过 AB
,但随后它说 A
未定义。
更新:
我发现了问题。
我有一个这样的类:
class A(object):
class B(object):
def __init__(self):
super(B, self).__init__()
someattribute = B()
在该范围内, A 尚未定义。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道为什么 AB 不能正常工作,因为它应该......以下是一些有效的 shell 输出:
I'm not sure why A.B is not working correctly for you, as it should.. Here's some shell output that works:
由于 B 可能永远不会扩展自身,因此这应该可行:
Since B will likely never be extended itself, this should work:
如果类 AB 不太可能参与任何多重继承,那么您最好只对构造函数调用进行硬编码:
但如果您确实需要拥有 super 的全部功能,那么您可以通过定义来获得您想要的将延迟初始化 B 属性的自定义描述符:
这将导致 B 属性在第一次访问时被实例化,然后重用:
有关描述符的更多信息,请参阅: rcn.com/python/download/Descriptor.htm" rel="nofollow noreferrer">http://users.rcn.com/python/download/Descriptor.htm
If the class A.B is unlikely to participate in any multiple inheritance, then you're better off just hard-coding the constructor call:
But if you really do need to have the full power of super, then you can get what you want by defining a custom descriptor that will initialize the B attribute lazily:
This will cause the B attribute to be instantiated the first time it's accessed, and then reused thereafter:
For more info on descriptors, see: http://users.rcn.com/python/download/Descriptor.htm