python的继承与多态
生活随笔
收集整理的這篇文章主要介紹了
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的继承与多态的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux学习之Linux历史
- 下一篇: Python学习笔记(序列和元组)