python多重继承

We are going to learn about python multiple inheritance today. Before starting multiple inheritance, I suggest you to skim through Python Class and Python Inheritance if you are not familiar with them.

今天我们将学习python多重继承。 在开始多重继承之前,如果您不熟悉Python类和Python继承 ,建议您先略读一下。

Python多重继承 (Python Multiple Inheritance)

The name says it all. One class extending more than one class is called multiple inheritance. This is one of the cool specialties of python which makes it more convenient than java in some cases (Java doesn’t support multiple inheritance). Java doesn’t have it because at times multiple inheritance may create some ambiguity. We shall talk about it later in this tutorial.

这个名字说明了一切。 一类扩展一个以上的类称为多重继承。 这是python的很酷的特色之一,在某些情况下,它比java更加方便(Java不支持多重继承)。 Java没有它,因为有时多重继承可能会产生一些歧义。 我们将在本教程的后面部分讨论它。

多重继承与多层次继承 (Multiple Inheritance vs Multi-level Inheritance)

It may seem confusing if you are familiar with multi-level inheritance before. The main difference between multiple and multi-level inheritance is that, in multi-level inheritance the superclass may also inherit another super class. And in this way, different levels of inheritance can be created among the classes.

如果您以前熟悉多级继承,可能会感到困惑。 多级继承和多级继承之间的主要区别在于,在多级继承中,超类还可以继承另一个超类。 这样,可以在类之间创建不同级别的继承。

Python多重继承范例 (Python Multiple Inheritance Example)

Let’s demonstrate a short example of python multiple inheritance.

让我们演示python多重继承的简短示例。

#definition of the class starts here
class Person:  #defining constructor  def __init__(self, personName, personAge):  self.name = personName  self.age = personAge  #defining class methods  def showName(self):  print(self.name)  def showAge(self):  print(self.age)  #end of class definition  # defining another class
class Student: # Person is the  def __init__(self, studentId):  self.studentId = studentId  def getId(self):  return self.studentId  class Resident(Person, Student): # extends both Person and Student class  def __init__(self, name, age, id):  Person.__init__(self, name, age)  Student.__init__(self, id)  # Create an object of the subclass
resident1 = Resident('John', 30, '102')
resident1.showName()
print(resident1.getId())

The classes Person and Student are superclass here and Resident is the subclass. The class Resident extends both Person and Student to inherit the properties of both classes. The example is easily understandable if you have the slightest knowledge of python class and python inheritance. This code yields the following output.

这里的Person和Student类是超类,Resident类是子类。 Resident类将Person和Student扩展为继承这两个类的属性。 如果您最了解python类和python继承,则该示例很容易理解。 此代码产生以下输出。

/usr/bin/python3.5 "/home/imtiaz/PycharmProjects/python tutorial - 1/multiple_inheritance.py"
John
102Process finished with exit code 0

使用python多重继承解决冲突 (Resolving the Conflicts with python multiple inheritance)

Let’s have a look at another example.

让我们看另一个例子。

class A:  def __init__(self):  self.name = 'John'  self.age = 23  def getName(self):  return self.name  class B:  def __init__(self):  self.name = 'Richard'  self.id = '32'  def getName(self):  return self.name  class C(A, B):  def __init__(self):  A.__init__(self)  B.__init__(self)  def getName(self):  return self.name  C1 = C()
print(C1.getName())

Class C inherits both A and B. And both of them has an attribute ‘name’. From which class the value of name will be inherited in C? Is it from A or B? What do you think? Well, the output is:

C类继承了A和B。它们都具有属性“名称”。 name的值将从哪个类继承自C? 是来自A还是来自B? 你怎么看? 好,输出为:

/usr/bin/python3.5 "/home/imtiaz/PycharmProjects/python tutorial - 1/multiple_inheritance.py"
RichardProcess finished with exit code 0

The name when printed is ‘Richard’ instead of ‘John’. Let’s try to understand what’s happening here. In the constructor of C, the first constructor called is the one of A. So, the value of name in C becomes same as the value of name in A. But after that, when the constructor of B is called, the value of name in C is overwritten by the value of name in B. So, the name attribute of C retains the value ‘Richard’ when printed. The result would be same even if we declared class C as:

打印时的名称是“ Richard”而不是“ John”。 让我们尝试了解这里发生的事情。 在C的构造函数中,第一个调用的构造函数是A的构造函数。因此,C中的name值与A中的name值相同。但是此后,当调用B的构造函数时,name的值C中的name被B中的name值覆盖。因此,C的name属性在打印时保留值'Richard'。 即使我们将C类声明为:

Class C(B, A):

The hierarchy becomes completely depended on the order of __init__() calls inside the subclass. To deal with it perfectly, there is a protocol named MRO (Method Resolution Order).

层次结构完全取决于子类内部__init __()调用的顺序。 为了完美地处理它,有一个名为MRO(方法解析顺序)的协议。

方法解析顺序(MRO) (Method Resolution Order (MRO))

Let’s replace the previous code with a slightly modified version.

让我们用稍微修改的版本替换之前的代码。

class A:  def __init__(self):  super().__init__()  self.name = 'John'  self.age = 23  def getName(self):  return self.name  class B:  def __init__(self):  super().__init__()  self.name = 'Richard'  self.id = '32'  def getName(self):  return self.name  class C(A, B):  def __init__(self):  super().__init__()  def getName(self):  return self.name  C1 = C()
print(C1.getName())

Can you guess the output? Well, let’s find out.

你能猜出输出吗? 好吧,让我们找出答案。

/usr/bin/python3.5 "/home/imtiaz/PycharmProjects/python tutorial - 1/multiple_inheritance.py"
JohnProcess finished with exit code 0

MRO works in a depth first left to right way. super() in the __init__ method indicates the class that is in the next hierarchy. At first the the super() of C indicates A. Then super in the constructor of A searches for its superclass. If it doesn’t find any, it executes the rest of the code and returns. So the order in which constructors are called here is:
C -> A -> B
If we call print(C.__mro__), then we can see the MRO traceroute.

MRO的工作深度从左到右。 __init__方法中的super()指示下一个层次结构中的类。 首先,C的super()表示A。然后,A的构造函数中的super搜索其超类。 如果找不到任何内容,它将执行其余代码并返回。 因此,此处调用构造函数的顺序为:
C-> A-> B
如果我们调用print(C .__ mro__),则可以看到MRO跟踪路由。

(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)

Once the constructor of A is called and attribute ‘name’ is accessed, it doesn’t access the attribute ‘name’ in B. A better understanding of MRO is a must in order to work with python multiple inheritance.

一旦调用了A的构造函数并访问了属性“名称”,它就不会访问B中的属性“名称”。要使用python多重继承,必须更好地理解MRO。

So this was it for python multiple inheritance, hope to come with more interesting features of python afterwards. Happy Coding!

因此,这就是python多重继承,希望以后再提供python的更多有趣功能。 编码愉快!

Reference: Python Doc

参考: Python文档

翻译自: https://www.journaldev.com/14623/python-multiple-inheritance

python多重继承

python多重继承_Python多重继承相关推荐

  1. pythonsuper多重继承_python多重继承实例 python多重继承下super问题

    python的多重继承问题有些事,有些人,有些风景,一旦入眼入心,即便刹那,也是永恒.当生活心怀歹毒地将一切都搞成了黑色幽默,小编顺水推舟把自己变成了一个受过高等教育的流氓. 楼上的回答的很正确,简单 ...

  2. pythonsuper多重继承_Python多重继承引发的问题——牛逼的super

    少说废话多做事先上一个图,此图用win7下的画图工具所画,当然,这不是重点 需要清楚的一个事情是: 任何类,都默认并隐式的继承object类(根类),在上面的图中,Transformers类同时继承了 ...

  3. python super 多重继承_解决python super()调用多重继承函数的问题

    当类间继承关系很简单时,super()的使用很简单. class A(object): def __init__(self): print('a') class B(A): def __init__( ...

  4. python小_python小记

    查找替换 ctrl + r 注释 ctrl+/ 格式化代码 ctrl+alt+l 跳转到定义 ctrl+alt+b 常用数据类型 数值类型:int float是两个比较常用的数值类型. Bool类型. ...

  5. python画代码-Python教程_Python画Mandelbrot集 代码

    Python教程_Python画Mandelbrot集 代码 作者:Comet 来源: 课课家 www.kokojia.com点击数:278发布时间:2015-06-19 11:17:19 曼德勃罗集 ...

  6. c语言实现爬虫功能,用C/C 扩展Python语言_python 调用c语言 python实现简单爬虫功能_python实现简单爬虫...

    用C/C 扩展Python语言 Python是一门功能强大的脚本语言,它的强大不仅表现在功能上,还表现在其扩展性上.她提供大量的API以方便程序员利用C/C++对Python进行扩展.因为执行速度慢几 ...

  7. python编程语言_python编程语言的简要历史

    python编程语言 The Python programming language is a general-purpose programming language that has carved ...

  8. 2019最新Python学习教程(Python视频教程_Python学习教程_Python学习路线):你心目中编程界的MVP是谁?

    2019最新Python学习教程(Python视频教程_Python学习教程_Python学习路线):你心目中编程界的MVP是谁?编程界的王者是渐落寞的Java还是大火的Python? 是不是你们也喜 ...

  9. python多继承顺序_Python多重继承方法解析顺序(MRO构建算法)

    分界 python的MRO算法有新旧两种,但并不是以python2和python3为界,具体的分隔为:在python2中如果定义类的时候没有指定父类是object,即定义为 class A: pass ...

最新文章

  1. 【LeetCode】414.第三大的数
  2. 源代码主干分支开发四大模式
  3. ajax多文件上传,js限制上传文件大小,文件上传前在浏览器展示
  4. mpvue初体验-用vue开发小程序
  5. c++中求解非线性方程组_齐次线性方程组的基础解系的简便算法
  6. 遗留问题,排雷会炸,不排也会炸!
  7. MS SQL 语法大全
  8. Python学习笔记:初识Tushare
  9. python入门教程pdf-《python基础教程(第3版)》高清版PDF免费下载
  10. c 字符串数组_C语言探索之旅 | 第二部分第四课:字符串
  11. [转]jQuery为控件添加水印文字
  12. win10计算机管理员权限删除,win10需要管理员权限删除文件怎么办?获取管理员权限删除文件夹...
  13. Ansible9:变量之Fact
  14. 需要精读3遍的8个健身知识
  15. 【正点原子FPGA连载】第三十九章OV7725摄像头RGB-LCD显示实验 -摘自【正点原子】新起点之FPGA开发指南_V2.1
  16. 1024,错过这一波福利,又要等一年了!
  17. 中国电信9月在京推5G新号段,资费199元至599元?
  18. 软件测试b s环境如何配置,B/S架构测试环境搭建_SQLServer篇(Win32系统)
  19. 台式机插上耳机没有声音
  20. 一种近似AMP音频增益转dB的优化写法:20.0*log10(amp)

热门文章

  1. C#中自己动手创建一个Web Server(非Socket实现)
  2. volatile 变量
  3. 语音信号处理基础(一)
  4. [转载] Python dict.keys方法
  5. [转载] python numpy np.finfo()函数 eps
  6. springmvc线程安全问题
  7. 9-21 调试javaweb 数据库连接感想
  8. Yoga安装Ubuntu后,wifi和亮度调节问题
  9. 如何查看Windows8.1计算机体验指数评分
  10. K210系列开发板介绍