# Python 繼承與多態
> 原文: [https://thepythonguru.com/python-inheritance-and-polymorphism/](https://thepythonguru.com/python-inheritance-and-polymorphism/)
* * *
于 2020 年 1 月 7 日更新
* * *
繼承允許程序員首先創建一個通用類,然后再將其擴展為更專業的類。 它還允許程序員編寫更好的代碼。
使用繼承,您可以繼承所有訪問數據字段和方法,還可以添加自己的方法和字段,因此繼承提供了一種組織代碼的方法,而不是從頭開始重寫代碼。
在面向對象的術語中,當`X`類擴展了`Y`類時,則`Y`被稱為*超類*或*基類*,而`X`被稱為*子類或派生類*。 還有一點要注意,子類只能訪問非私有的數據字段和方法,私有數據字段和方法只能在該類內部訪問。
創建子類的語法是:
```py
class SubClass(SuperClass):
# data fields
# instance methods
```
讓我們以一個例子來說明這一點。
```py
class Vehicle:
? ? def __init__(self, name, color):
? ? ? ? self.__name = name ? ? ?# __name is private to Vehicle class
self.__color = color
? ? def getColor(self): ? ? ? ? # getColor() function is accessible to class Car
? ? ? ? return self.__color
? ? def setColor(self, color): ?# setColor is accessible outside the class
? ? ? ? self.__color = color
? ? def getName(self): # getName() is accessible outside the class
? ? ? ? return self.__name
class Car(Vehicle):
? ? def __init__(self, name, color, model):
# call parent constructor to set name and color
? ? ? ? super().__init__(name, color) ?
? ? ? ? self.__model = model
? ? def getDescription(self):
? ? ? ? return self.getName() + self.__model + " in " + self.getColor() + " color"
# in method getDescrition we are able to call getName(), getColor() because they are
# accessible to child class through inheritance
c = Car("Ford Mustang", "red", "GT350")
print(c.getDescription())
print(c.getName()) # car has no method getName() but it is accessible through class Vehicle
```
**預期輸出**:
```py
Ford MustangGT350 in red color
Ford Mustang
```
在這里,我們創建了基類`Vehicle`及其子類`Car`。 注意,我們沒有在`Car`類中定義`getName()`,但是我們仍然可以訪問它,因為類`Car`從`Vehicle`類繼承。 在上面的代碼中,`super()`方法用于調用基類的方法。 這是`super()`的工作方式
假設您需要在子類的基類中調用名為`get_information()`的方法,則可以使用以下代碼進行調用。
```py
super().get_information()
```
同樣,您可以使用以下代碼從子類構造器中調用基類構造器。
```py
super().__init__()
```
## 多重繼承
* * *
與 Java 和 C# 等語言不同,python 允許多重繼承,即您可以同時從多個類繼承,
```py
class Subclass(SuperClass1, SuperClass2, ...):
? ?# initializer
? # methods
```
讓我們舉個例子:
```py
class MySuperClass1():
? ? def method_super1(self):
? ? ? ? print("method_super1 method called")
class MySuperClass2():
? ? def method_super2(self):
? ? ? ? print("method_super2 method called")
class ChildClass(MySuperClass1, MySuperClass2):
? ? def child_method(self):
? ? ? ? print("child method")
c = ChildClass()
c.method_super1()
c.method_super2()
```
**預期輸出**:
```py
method_super1 method called
method_super2 method called
```
如您所見,因為`ChildClass`繼承了`MySuperClass1`,`MySuperClass2`,所以`ChildClass`的對象現在可以訪問`method_super1()`和`method_super2()`。
## 覆蓋方法
* * *
要覆蓋基類中的方法,子類需要定義一個具有相同簽名的方法。 (即與基類中的方法相同的方法名稱和相同數量的參數)。
```py
class A():
? ? def __init__(self):
? ? ? ? self.__x = 1
? ? def m1(self):
? ? ? ? print("m1 from A")
class B(A):
? ? def __init__(self):
? ? ? ? self.__y = 1
? ? def m1(self):
? ? ? ? print("m1 from B")
c = B()
c.m1()
```
**預期輸出**:
```py
m1 from B
```
在這里,我們從基類中重寫`m1()`方法。 嘗試在`B`類中注釋`m1()`方法,現在將運行`Base`類中的`m1()`方法,即`A`類。
**預期輸出**:
```py
m1 from A
```
## `isinstance()`函數
* * *
`isinstance()`函數用于確定對象是否為該類的實例。
**語法**: `isinstance(object, class_type)`
```py
>>> isinstance(1, int)
True
>>> isinstance(1.2, int)
False
>>> isinstance([1,2,3,4], list)
True
```
下一章[異常處理](/python-exception-handling/)。
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象