多態:同一種事物的多種形態(被繼承的子類)
class Animal(metaclass=abc.ABCMeta):#同一種事物:動物
@abc.abstractclassmethod
def run(self):
pass
class People(Animal):#動物形態之一
def run(self):
print('is running ')
class Pig(Animal):#形態之二
def run(self):
print('is running ')
class Dog(Animal):#形態三
def eat(self):
print('is eating')
多態動態綁定(在繼承時,又叫做多態性)。
多態性是在可以不考慮實例類型的情況下使用實例,分爲動態多態和靜態多態
//不考慮是人是狗是豬,不考慮是什麼類,只考慮父類的特性,忽視本身的形態
動態多態:
peo1 = People()
pig1 = Pig()
dog1 = Dog()
peo1.run()
pig1.run()
dog1.run()
靜態多態:
舉例:加號。字符串加號字符串,或者數字加數字。並不關心字符串本身,關鍵是加號。
好處:
# peo1.run()
# pig1.run()
# dog1.run()
def func(animal):
animal.run()
func(peo1)
func(pig1)
func(dog1)
取消每個實例化的對象直接調用函數,忽視實例化對象作爲形態的特點,將他們全部用同一個接口func()管理,不必考慮是人是豬是狗。效率更高。
車子,有寶馬奔馳、摩托車、拖拉機等等。學的時候學的是車,不是寶馬也不是奔馳,只是學習車子的操作。學完開車之後什麼車都能開,只是這些車都有細微的區別而已。
- 增加靈活性,只用少數的接口管理(建立在多態之上)
- 增加了擴展性(新增類的時候直接使用管理調用就好)
鴨子類型
長的像鴨子,叫聲像鴨子,走路像鴨子,那你就是鴨子。
可以繼承或者創建一個外觀、行爲等相似的類,但他們毫無聯繫。通常可以保存程序組合的耦合程度
class File:
def read(self):
pass
def write(self):
pass
class Disk:
def read(self):
print('disk read')
def write(self):
print('disk write')
class Text:
def read(self):
print('text read')
def write(self):
print('text write')
disk = Disk()
text =Text()
disk.read()
disk.write()
text.read()
text.write()
disk 和 text兩個類與file沒有關係,但是可以看成有關係,作爲文件讀和寫。因爲看起來和File一樣,因此可以和Flie一樣使用它。
不必非有父類約束它