Day 5-3 多态与多态性

多态与多态性

鸭子类型

多态与多态性

多态:一类事物有多种形态.比如,动物有多种形态,人,狗,猪,豹子.水也有多种形态,冰,雪,水蒸气.

 1 #多态:同一类事物的多种形态
 2 import abc
 3 class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
 4     @abc.abstractmethod
 5     def talk(self):
 6         pass
 7 
 8 class People(Animal): #动物的形态之一:人
 9     def talk(self):
10         print('say hello')
11 
12 class Dog(Animal): #动物的形态之二:狗
13     def talk(self):
14         print('say wangwang')
15 
16 class Pig(Animal): #动物的形态之三:猪
17     def talk(self):
18         print('say aoao')
19 
20 class Cat(Animal):
21     def talk(self):
22         print('say miamiao')
23 
24 #多态性:指的是可以在不考虑对象的类型的情况下而直接使用对象
25 peo1=People()
26 dog1=Dog()
27 pig1=Pig()
28 cat1=Cat()
29 
30 # peo1.talk()
31 # dog1.talk()
32 # pig1.talk()
33 
34 def func(animal):
35     animal.talk()
func(peo1) # 不用考虑peo1到底是猪狗人,还是其他的类型,直接可以通过这个统一的func函数来调用执行.

多态性的好处:

1.增加了程序的灵活性

  以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal)

2.增加了程序额可扩展性

 通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal)去调用  

鸭子类型:

即,如果看起来像鸭子,走路像鸭子而且叫起来像鸭子,那么就是鸭子.

 1 #二者都像鸭子,二者看起来都像文件,因而就可以当文件一样去用
 2 class TxtFile:
 3     def read(self):
 4         print("text is reading")
 5 
 6     def write(self):
 7         pass
 8 
 9 class DiskFile:
10     def read(self):
11        print("disk is reading")
12     def write(self):
13         pass
14 
15 text = TxtFile()
16 disk = DiskFile()
17 
18 text.read()
19 disk.read()

 鸭子类型,不用继承抽象类,只需要把2个类型里的方法属性写的相像.就可以了.

原文地址:https://www.cnblogs.com/lovepy3/p/8971838.html