python面向对象:多态

python面向对象:多态

多态的应用场景

1. 对象所属的类之间没有继承关系

调用同一个函数fly(), 传入不同的参数(对象),可以达成不同的功能

class Duck(object):                                  # 鸭子类
    def fly(self):
        print("鸭子沿着地面飞起来了")

class Swan(object):                                  # 天鹅类
    def fly(self):
        print("天鹅在空中翱翔")

class Plane(object):                                 # 飞机类
    def fly(self):
        print("飞机隆隆地起飞了")

def fly(obj):                                        # 实现飞的功能函数
    obj.fly()

duck = Duck()
fly(duck)

swan = Swan()
fly(swan)

plane = Plane()
fly(plane)

===运行结果:===================================================================================
鸭子沿着地面飞起来了
天鹅在空中翱翔
飞机隆隆地起飞了

2. 对象所属的类之间有继承关系(应用更广)

class gradapa(object):
    def __init__(self,money):
        self.money = money
    def p(self):
        print("this is gradapa")
 
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
         
#定义一个函数,函数调用类中的p()方法
def fc(obj): 
    obj.p()
gradapa1 = gradapa(3000) 
father1 = father(2000,"工人")
mother1 = mother(1000,"老师")

fc(gradapa1)            #这里的多态性体现是向同一个函数,传递不同参数后,可以实现不同功能.
fc(father1)
print(fc(mother1))
===运行结果:===================================================================================
this is gradapa
this is father,我重写了父类的方法
this is mother,我重写了父类的方法
100

总结如下:

多态性依赖于:继承
综合来说:多态性:定义统一的接口,一种调用方式,不同的执行效果(多态性)
# obj这个参数没有类型限制,可以传入不同类型的值   ;参数obj就是多态性的体现
def func(obj):    
    obj.run()        # 调用的逻辑都一样,执行的结果却不一样


class A (object):
     def run(self):
         pass       


class A1 (A):
     def run(self):
         print ('开始执行A1的run方法')
class A2 (A):
     def run(self):
         print ('开始执行A2的run方法')
class A3 (A):
     def run(self):
         print ('开始执行A3的run方法')

obj1
= A1 () obj2 = A2 () obj3 = A3 () func(obj1) 输出:开始执行A1的run方法 func(obj2)    输出:开始执行A2的run方法 func(obj3)    输出:开始执行A3的run方法


原文地址:https://www.cnblogs.com/111testing/p/13985300.html