Python - 面向对象编程 - 多继承

时间:2021-09-06 00:20:26   收藏:0   阅读:40

继承的详解

https://www.cnblogs.com/poloyy/p/15216652.html

这篇文章讲的都是单继承,Python 中还有多继承

 

Python 多继承的背景

 

什么是多继承

 

语法格式

class 子类(父类1, 父类2, ...):
    pass

  

类图参考

技术分享图片

  

实际代码

class A:
    def test(self):
        print("test")


class B:
    def demo(self):
        print("demo")


class C(A, B):
    ...


c = C()
c.test()
c.demo()


# 输出结果
test
demo

 C 继承了 A、B,拥有了他们的所有属性和方法

 

多继承带来的顺序问题

问题的提出

如果不同的父类中存在同名的方法,子类对象在调用该方法时,会调用哪一个父类的方法呢?

 

重点注意

 

类图

技术分享图片

 

实际代码

class A:
    def test(self):
        print("AAA-test")

    def demo(self):
        print("AAA-demo")

class B:
    def test(self):
        print("BBB-test")

    def demo(self):
        print("BBB-demo")


class C(A, B):
    ...


c = C()
c.test()
c.demo()


# 输出结果
AAA-test
AAA-demo

调用的是父类 A 的方法

 

如果 C 继承父类的顺序改变一下呢

# 刚刚是 A, B ; 现在是 B, A
class C(B, A):
    ...


c = C()
c.test()
c.demo()


# 输出结果
BBB-test
BBB-demo

 

Python 的 MRO 方法搜索顺序

https://www.cnblogs.com/poloyy/p/15226424.html

 

多继承结合 super() 的使用呢?

https://www.cnblogs.com/poloyy/p/15223443.html

 

新式类和旧式类

https://www.cnblogs.com/poloyy/p/15226425.html

 

原文:https://www.cnblogs.com/poloyy/p/15224912.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!