【问题标题】:Python : super key word calling from child classPython:从子类调用超级关键字
【发布时间】:2017-02-22 15:06:35
【问题描述】:
class Parent01(object):
    def foo(self):
        print("Parent01")
        pass

class Parent02(object):
    def foo(self):
        print("Parent02")
        pass

class Child(Parent01,Parent02):
    def foo(self):
        print("Child")
        super(Parent01, self).foo()
    pass

c = Child()
c.foo()

输出:

Child
Parent02

为什么这里是输出Parent02

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您误用了super。你应该命名你的 own 类,而不是父类。鉴于这是 Python 3,您甚至不需要这样做,很简单:

super().foo()

会起作用(只要函数的第一个参数是单个参数,无论名称如何;当您通过*args 接受self 时有例外情况,但这种情况很少见,并且仅适用于复杂情况涉及模拟dict)。

它行为不端的原因是你已经明确告诉它你正在做基于Parent01super,而不是Child,所以它扫描the MRO (method resolution order)以查找Parent01之后的下一个类,恰好是Parent02

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 1970-01-01
    • 2011-02-05
    • 2012-09-10
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多