Python多重继承

多重继承可以允许继承多个父类,实现多个父类的功能,具体可以参考这里

那么若当多个父类有相同的方法时,调用这个方法会如何。
答:会调用继承第一个类中的方法。这是按照Python方法解决顺序执行,参考如下代码。

class A:
    def say_hello(self):
        print("Hi from A")

class B:
    def say_hello(self):
        print("Hello from B")

class C(A, B):
    def say_hello(self):
        super().say_hello()


welcome = C()
print("the method resolution order: {}".format(C.__mro__))
welcome.say_hello()

运行结果为:

the method resolution order: (<class ‘main.C’>, <class ‘main.A’>, <class ‘main.B’>, <class ‘object’>)
Hi from A

如果需要调用每个父类的方法,可以明确写明调用。

class C(A, B):
    def say_hello(self):
        A.say_hello(self)
        B.say_hello(self)

更详细可以参见Stack Overflow

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值