继承(派生)
子类继承父类的属性与方法,所有类都默认继承object类
能够提高代码的复用性,但耦合性增强、会继承到不需要的属性与方法
派生是从父类角度来描述继承的,即从已有的类产生新的类
父类被称为基类,子类叫为派生类、扩展类
1 2 3 4 5 6 7 8 9 10 11
| class Parent: def __init__(self,money): self.money=money def consumption(self,money): self.money-=money print(self.money) class Children(Parent): pass if __name__=="__main__": c1=Children(100) c1.consumption(100)
|
单继承
一个子类只能继承自一个父类,不能继承多个类
上述代码中体现的是单继承,Children类只有一个父类
多继承
多继承中就是一个类同时继承了多个父类,同时具有所有父类的属性和方法
注意:存在MRO机制,当有多个父类时,默认使用第一个父类的同名属性和方法,可以使用**类名.mro()或者类名.mro**属性来查看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Parent: def __init__(self,money): self.money=money def consumption(self,money): self.money-=money print(self.money) class Man: def __init__(self): self.leg=2 self.eyes=2 class Children(Parent,Man): def __init__(self,money): Parent.__init__(self, money) Man.__init__(self) if __name__=="__main__": c1=Children(100) c1.consumption(100) print(Children.mro()) print(c1.eyes) """ 0 [<class '__main__.Children'>, <class '__main__.Parent'>, <class '__main__.Man'>, <class 'object'>] 2 """
|
子类重写父类同名方法(属性)
即在子类定义中使用父类的同名方法(属性)会被覆盖,依旧参考mro机制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Parent: def __init__(self,money): self.money=money def consumption(self,money): self.money-=money print(self.money) class Man: def __init__(self): self.leg=2 self.eyes=2 class Children(Parent,Man): def __init__(self,money): Parent.__init__(self, money) Man.__init__(self) self.leg=1 if __name__=="__main__": c1=Children(100) c1.consumption(100) print(c1.leg,c1.eyes)
|
子类调用特定父类方法
在子类中定义新方法并调用特定父类方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Parent: def __init__(self,money): self.money=money def consumption(self,money): self.money-=money print(self.money) class Man: def __init__(self,money): self.leg=2 self.eyes=2 self.money=money def consumption(self,money): self.money+=money print(self.money) class Children(Parent,Man): def __init__(self,money): Parent.__init__(self, money) Man.__init__(self, money) self.leg=1 def man_consumption(self,money): Man.consumption(self,money) if __name__=="__main__": c1=Children(100) c1.man_consumption(100)
|
也能使用**super().父类方法名(self)**来调用父类方法,只能调用首位父类的方法,适合单继承,不适合多继承
多层继承
即类A继承类B、类B继承类C,这就是多层继承
开发原则
高内聚、低耦合
即类的独立性要高,依赖性低