日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python的继承与多态

發布時間:2024/7/23 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python的继承与多态 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一,繼承?

class Person(object):def __init__(self, name, sex):self.name = nameself.sex = sexdef print_title(self):if self.sex == "male":print("man")elif self.sex == "female":print("woman")class Child(Person): # Child 繼承 PersonpassLice = Child("Lice", "female") Peter = Person("Peter", "male")print(Lice.name, Lice.sex, Peter.name, Peter.sex) # 子類繼承父類方法及屬性 Lice.print_title() Peter.print_title()

二,多態,重寫父類方法

class Person(object):def __init__(self, name, sex):self.name = nameself.sex = sexdef print_title(self):if self.sex == "male":print("man")elif self.sex == "female":print("woman")class Child(Person): # Child 繼承 Persondef print_title(self):if self.sex == "male":print("boy")elif self.sex == "female":print("girl")Lice = Child("May", "female") Peter = Person("Peter", "male")print(Lice.name, Lice.sex, Peter.name, Peter.sex) Lice.print_title() Peter.print_title()

三,子類重寫構造函數

class Person(object):def __init__(self,name,sex):self.name = nameself.sex = sexclass Child(Person): # Child 繼承 Persondef __init__(self,name,sex,mother,father):self.name = nameself.sex = sexself.mother = motherself.father = fatherLice = Child("Lice","female","Haly","Peter") print(Lice.name,Lice.sex,Lice.mother,Lice.father)

四,父類構造函數包含很多屬性,子類僅需新增1、2個,會有不少冗余的代碼,這邊,子類可對父類的構造方法進行調用

class Person(object):def __init__(self,name,sex):self.name = nameself.sex = sexclass Child(Person): # Child 繼承 Persondef __init__(self,name,sex,mother,father):Person.__init__(self,name,sex) # 子類對父類的構造方法的調用self.mother = motherself.father = father# self.name='haha'Lice = Child("Lice","female","Haly","Peter") print(Lice.name,Lice.sex,Lice.mother,Lice.father)

?

五,多重繼承,新建一個類 baby 繼承 Child , 可繼承父類及父類上層類的屬性及方法,優先使用層類近的方法,

#coding:utf-8 class Person(object):def __init__(self, name, sex):self.name = nameself.sex = sexdef print_title(self):if self.sex == "male":print("man")elif self.sex == "female":print("woman")class Child(Person):passclass Baby(Child):passLice = Baby("Lice", "female") # 繼承上上層父類的屬性 print(Lice.name, Lice.sex) Lice.print_title() # 可使用上上層父類的方法print('==================') class Child(Person):def print_title(self):if self.sex == "male":print("boy")elif self.sex == "female":print("girl")class Baby(Child):passLice2 = Baby("Lice2", "female") print(Lice2.name, Lice2.sex) Lice2.print_title() # 優先使用上層類的方法

?

創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

總結

以上是生活随笔為你收集整理的python的继承与多态的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。