12.2 类的派生
1.类的查找顺序
#父类
class Foo:def f1(self):print('Foo.f1')def f2(self): #bprint('Foo.f2')self.f1()#子类
class Bar(Foo):def f1(self):print('Bar.f1')b = Bar()
b.f2() #查找顺序:Bar()->Foo.f2()->输出Foo.f2->bar.f1()->输出Bar.f1#输出
Foo.f2
Bar.f1
Foo.f2
Bar.f1
2. 类的派生
添加新的属性的同时还有继承父类的所有东西
#方法1:
class Animal():def __init__(self,height,weight):self.height=heightself.weight=weightdef jiao(self):print(self.__class__.__name__,'叫')
# Animal.__init__(111,185,140) #类调用传3个参数,对象调用传2个参数class People(): def __init__(self,name,age,height,weight):Animal.__init__(self,height,weight)self.name=nameself.age=agedef read(self):print('read')def sleep(self):print(f'self_sleep')peo=People('coco',18,185,140)print(peo.__dict__)
{'height': 185, 'weight': 140, 'name': 'coco', 'age': 18}
方法1总结:
- 不需要继承也可以做到
- 派生:继承父类属性的同时增加新的属性, 然后使用
- 引出方法2,方法2对方法1进行封装
#方法2:(重点)
class Animal():def __init__(self,height,weight):self.height=heightself.weight=weightdef jiao(self):print(self.__class__.__name__,'叫')class People(Animal): def __init__(self,name,age,height,weight):super().__init__(height,weight) #规定的语法super会自动调用父类的__init__,并且拿到height、weightself.name=nameself.age=agedef read(self):print('read')def sleep(self):print(f'self_sleep')
peo=People('coco',18,185,140)print(peo.__dict__)
{'height': 185, 'weight': 140, 'name': 'coco', 'age': 18}
方法2总结:继承才可以
- super().init(height,weight)
尽量只继承一个父类,遵从线性继承的规则。
#继承XingXing的gender
class Animal():def __init__(self,height,weight):self.height=heightself.weight=weightdef jiao(self):print(self.__class__.__name__,'叫')class XingXing(Animal): #继承Animaldef __init__(self,height,weight,gender):super().__init__(height,weight)self.gender=genderdef sleep(self):print('sleep')class People(XingXing): #继承XingXing def __init__(self,name,age,height,weight,gender):super().__init__(height,weight,gender) self.name=nameself.age=agedef read(self):print('read')def sleep(self):print(f'self_sleep')
peo=People('coco',18,185,140,'male')print(peo.__dict__)#线性继承:People继承XingXing,XingXing继承Animal。
{'height': 185, 'weight': 140, 'gender': 'male', 'name': 'coco', 'age': 18}