Python 多重繼承 multiple inheritance

本篇介紹 Python 多重繼承 multiple inheritance 的寫法,

Python 多重繼承(Multiple Inheritance)的寫法

Python multiple inheritance 最簡單的多重繼承寫法如下,
有 BaseClass1, BaseClass2, DerivedClass 三個類別
DerivedClass 多重繼承 BaseClass1 和 BaseClass2

python-multiple-inheritance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class BaseClass1:
pass

class BaseClass2:
pass

class DerivedClass(BaseClass1, BaseClass2):
pass

derived = DerivedClass()

方法覆寫(Method Overriding)

Dog3 多重繼承了 Dog1 和 Dog2,如果沒有覆寫父類的 eat,呼叫子類 Dog3.eat() 時會繼承的前面/左邊父類(Dog1)方法優先,

python-multiple-inheritance2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Dog1:
def eat(self):
print("Dog1 class eat method is called.")

class Dog2:
def eat(self):
print("Dog2 class eat method is called.")

class Dog3(Dog1, Dog2):
pass

dog = Dog3()
dog.eat()

結果輸出如下,

1
Dog1 class eat method is called.

子類建構子(Constructor)傳遞參數到父類建構子

在多重繼承的情況下,子類建構子又是如何傳遞參數到父類的建構子,這邊來介紹一下,
呼叫

python-multiple-inheritance3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class Dog1:
def __init__(self, name):
print("Dog1 ", name)

def eat(self):
print("Dog1 class eat method is called.")

class Dog2:
def __init__(self, sex):
print("Dog2 ", sex)

def eat(self):
print("Dog2 class eat method is called.")

class Dog3(Dog2):
def __init__(self, sex):
print("Dog3 ", sex)
Dog2.__init__(self, sex)

def eat(self):
print("Dog3 class eat method is called.")

class Dog4(Dog1, Dog3):
def __init__(self, name, sex):
Dog1.__init__(self, name)
Dog3.__init__(self, sex)

#dog = Dog4(name="Harry", sex="female")
dog = Dog4("Harry", "female")
dog.eat()

結果輸出如下,

1
2
3
4
Dog1  Harry
Dog3 female
Dog2 female
Dog1 class eat method is called.

參考
Classes — Python 3.9.0 documentation
https://docs.python.org/3/tutorial/classes.html#multiple-inheritance
Python 速查手冊 - 6.9 多重繼承
http://kaiching.org/pydoing/py/python-multiple-inheritance.html
程式語言教學誌 FB, YouTube: PYDOING: Python 3.1 快速導覽 - 類別 多重繼承
https://pydoing.blogspot.com/2011/01/python-multiple.html
Python-QA/Python多重繼承屬性問題.md at master · dokelung/Python-QA
https://github.com/dokelung/Python-QA/blob/master/questions/object/Python%E5%A4%9A%E9%87%8D%E7%B9%BC%E6%89%BF%E5%B1%AC%E6%80%A7%E5%95%8F%E9%A1%8C.md

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 繼承
Python 新手入門教學懶人包
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 讓程式 sleep 延遲暫停時間