1. 程式人生 > 實用技巧 >python面向物件:多型

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方法