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学习笔记(序列和元组)