多态指的是一类事物有多种形态,一个类有不少个子类,于是多态的概念是基于继承的python
# 动物有多种形态:人类、猪、狗 class Animal: def run(self): # 子类约定俗称的必须实现这个方法 raise AttributeError('子类必须实现这个方法') class People(Animal): def run(self): print('人正在走') class Pig(Animal): def run(self): print('pig is walking') class Dog(Animal): def run(self): print('dog is running') peo1 = People() pig1 = Pig() d1 = Dog() peo1.run() pig1.run() d1.run()
人正在走
pig is walking
dog is running函数
import abc class Animal(metaclass=abc.ABCMeta): # 同一类事物:动物 @abc.abstractmethod # 上述代码子类是约定俗称的实现这个方法,加上@abc.abstractmethod装饰器后严格控制子类必须实现这个方法 def talk(self): raise AttributeError('子类必须实现这个方法') class People(Animal): # 动物的形态之一:人 def talk(self): print('say hello') class Dog(Animal): # 动物的形态之二:狗 def talk(self): print('say wangwang') class Pig(Animal): # 动物的形态之三:猪 def talk(self): print('say aoao') peo2 = People() pig2 = Pig() d2 = Dog() peo2.talk() pig2.talk() d2.talk()
say hello
say aoao
say wangwangcode
# 文件有多种形态:文件、文本文件、可执行文件 import abc class File(metaclass=abc.ABCMeta): # 同一类事物:文件 @abc.abstractmethod def click(self): pass class Text(File): # 文件的形态之一:文本文件 def click(self): print('open file') class ExeFile(File): # 文件的形态之二:可执行文件 def click(self): print('execute file') text = Text() exe_file = ExeFile() text.click() exe_file.click()
open file
execute file对象
# 多态性:一种调用方式,不一样的执行效果(多态性) def func(obj): obj.run() func(peo1) func(pig1) func(d1)
人正在走
pig is walking
dog is running继承
# 多态性依赖于:继承 # 多态性:定义统一的接口 def func(obj): # obj这个参数没有类型限制,能够传入不一样类型的值 obj.talk() # 调用的逻辑都同样,执行的结果却不同 func(peo2) func(pig2) func(d2)
say hello
say aoao
say wangwang接口
def func(obj): obj.click() func(text) func(exe_file)
open file
execute file字符串
def func(obj): print(len(obj)) func('hello') func([1, 2, 3]) func((1, 2, 3))
5class
3import
3cli
综上能够说,多态性是一个接口(函数func)的多种实现(如obj.run(),obj.talk(),obj.click(),len(obj))
其实你们从上面多态性的例子能够看出,咱们并无增长新的知识,也就是说Python自己就是支持多态性的,这么作的好处是什么呢?
class Cat(Animal): # 属于动物的另一种形态:猫 def talk(self): print('say miao') def func(animal): # 对于使用者来讲,本身的代码根本无需改动 animal.talk() cat1 = Cat() # 实例出一只猫 func(cat1) # 甚至连调用方式也无需改变,就能调用猫的talk功能
say miao
多态:同一种事物的多种形态,动物分为人类,猪类(在定义角度) 多态性:一种调用方式,不一样的执行效果(多态性)