概念
一种事物的多种体现形式,举例:动物有很多种。在Python中,多态指的是父类的引用指向子类的对象
class Animal(object): pass class Cat(Animal): pass class Pig(Animal): pass a = list() b = Animal() c = Cat() #isinstance(变量,类型) print(isinstance(a,list)) #True print(isinstance(b,Animal)) #True print(isinstance(c,Cat) #True print(isinstance(c,Animal)) #True print(isinstance(b,Pig)) #false
注意:继承是多态的前提,函数重写就是多态的体现形式。在继承关系中,如果一个对象的类型是某个子类,则它的数据类型也可以被看作是对应的父类,反之则不行
使用
需求:饲养员喂养猫和老鼠,老虎等动物
分析:
- 定义饲养员的类和动物的类
- 定义老鼠类,猫类等继承动物类
- 在饲养员中定义类成员函数,喂养
#使用多态,不同的子类对象可以共用一个函数 class Person(object): ''' def feedCat(self,cat): print("喂养" + cat.name) def feedMouse(self,mouse): print("喂养" + mouse.name) def feedTiger(self,tiger): print("喂养" + tiger.name) ''' def feedAnimal(self,ani): print("喂养" + ani.name) class Animal(object): def __init__(self,name): self.name = name def eat(self): print("eating") class Mouse(Animal): def __init__(self,name): super(Mouse,self).__init__(name) #1.创建一个饲养员的对象 p = Person() #2.创建Mouse的对象 m = Mouse("Tom") #3.饲养员执行自己的行为 p.feedAnimal(m) #喂养Tom