使用 super() 与非直接父级
这是 super() 的合法使用吗?
class A(object):
def method(self, arg):
pass
class B(A):
def method(self, arg):
super(B,self).method(arg)
class C(B):
def method(self, arg):
super(B,self).method(arg)
谢谢。
Is this a legal use of super()?
class A(object):
def method(self, arg):
pass
class B(A):
def method(self, arg):
super(B,self).method(arg)
class C(B):
def method(self, arg):
super(B,self).method(arg)
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它会起作用,但它可能会让任何试图阅读你的代码的人感到困惑(包括你,除非你特别记得它)。不要忘记,如果您想从特定父类调用方法,您可以这样做:
It will work, but it will probably confuse anyone trying to read your code (including you, unless you remember it specifically). Don't forget that if you want to call a method from a particular parent class, you can just do:
嗯,“合法”在这里是一个值得商榷的术语。该代码最终将调用
A.method
,因为赋予super
的类型被排除在搜索之外。至少可以说,我认为 super 的这种用法很不稳定,因为它会跳过继承层次结构的一个成员(看似随意),这与我作为开发人员的期望不一致。由于已经鼓励super
的用户保持一致性,因此我建议不要这种做法。Well, "legal" is a questionable term here. The code will end up calling
A.method
, since the type given tosuper
is excluded from the search. I would consider this usage ofsuper
flaky to say the least, since it will skip a member of the inheritance hierarchy (seemingly haphhazardly), which is inconsistent with what I would expect as a developer. Since users ofsuper
are already encouraged to maintain consistency, I'd recommend against this practice.