多态:同类对象的多种形态,一个接口多种实现,(以封装和继承为前提),不同的子类调用相同的方法,产生不同的结果
1.增加了程序的灵活性
以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal)
2.增加了程序额可扩展性
通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal)去调用
特点
1、只关心对象的实例方法是否同名,不关心对象所属的类型; 2、对象所属的类之间,继承关系可有可无; 3、多态的好处可以增加代码的外部调用灵活度,让代码更加通用,兼容性比较强; 4、多态是调用方法的技巧,不会影响到类的内部设计。
对象所属的类之间有继承关系
class Animal(object):
def __init__(self,name):
self.name=name
def talk(self):
print("Animal类的talk方法")
@staticmethod
def animal_talk(obj): #动物叫的接口
obj.talk()
class Cat(Animal):
def talk(self):
print("%s 喵喵叫"%self.name)
class Dog(Animal):
def talk(self):
print("%s 汪汪叫"%self.name)
c=Cat('小黑')
d=Dog('大黄')
print(c,d)
Animal.animal_talk(c)#多态:一个接口多种实现
Animal.animal_talk(d)
"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/Test/test03.py
<__main__.Cat object at 0x000001EB7D599A58> <__main__.Dog object at 0x000001EB7D599A90>
小黑 喵喵叫
大黄 汪汪叫
Process finished with exit code 0
class gradapa(object):
def __init__(self, money):
self.money = money
def p(self):
print("this is gradapa")
def fc(obj):
obj.p()
class father(gradapa):
def __init__(self, money, job):
super().__init__(money)
self.job = job
def p(self):
print("this is father,我重写了父类的方法")
class mother(gradapa):
def __init__(self, money, job):
super().__init__(money)
self.job = job
def p(self):
print("this is mother,我重写了父类的方法")
return 100
gradapa1 = gradapa(3000)
father1 = father(2000, "工人")
mother1 = mother(1000, "老师")
gradapa.fc(gradapa1) #这里的多态性体现是向同一个函数,传递不同参数后,可以实现不同功能.
gradapa.fc(father1)
gradapa.fc(mother1)
"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/Test/test03.py
this is gradapa
this is father,我重写了父类的方法
this is mother,我重写了父类的方法
Process finished with exit code 0
对象所属的类之间没有继承关系
class Duck(object): # 鸭子类
def fly(self):
print("鸭子沿着地面飞起来了")
def test(obj): # 实现飞的功能函数
obj.fly()
class Swan(object): # 天鹅类
def fly(self):
print("天鹅在空中翱翔")
class Plane(object): # 飞机类
def fly(self):
print("飞机隆隆地起飞了")
duck = Duck()
Duck.test(duck)
swan = Swan()
Duck.test(swan)
plane = Plane()
Duck.test(plane)
"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/Test/test03.py
鸭子沿着地面飞起来了
天鹅在空中翱翔
飞机隆隆地起飞了
Process finished with exit code 0