一.继承
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()
二.多态
1.重写父类方法
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()
2.子类重写构造函数
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)
3.子类对父类的构造方法进行调用
父类构造函数包含很多属性,子类仅需新增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)
class Person(object):def __init__(self, name, sex):self.name = nameself.sex = sexclass Child(Person): # Child 继承 Persondef __init__(self, name, sex, mother, father):super(Child, self).__init__(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)
4.多重继承
新建一个类 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() # 优先使用上层类的方法
5.替换if else
class Pay:def pay(self):raise NotImplementedErrorclass AliPay(Pay):def pay(self):print('==ali pay')class WechatPay(Pay):def pay(self):print('==wechat pay')lookup = {'alipay': AliPay(),'wechat': WechatPay()}def pay(pay_type):lookup.get(pay_type).pay()pay('alipay')