9、继承与多继承及及父类方法相关用法
1)继承
说明:
-
将多个父类放在子类之后的圆括号里。
class SubClass(SuperClass1, SuperClass2, ...): # 类定义部分
-
从子类角度来看,子类扩展了父类;从父类角度来看,父类派生出子类。
-
子类继承父类,可获得父类的方法。
class Fruit: def taste(self): print('水果营养丰富,味道可口') # Apple 继承了 Fruit class Apple(Fruit): pass a = Apple() a.taste() # 继承:子类可以直接复用父类的方法
水果营养丰富,味道可口
2)多继承
class Bird:
def able(self):
print('会飞')
class Pet:
def info(self):
print('漂亮')
class Parrot(Bird, Pet):
pass
b = Parrot()
b.able()
print('-'*30)
b.info()
会飞
------------------------------
漂亮
分析:若多个父类中包含了同名的方法,排在前面的父类中的方法会“遮蔽”排在后面的父类的同名方法。因此不推荐使用多继承。
class Bird:
def info(self):
print('羽毛')
class Pet:
def info(self):
print('漂亮')
class Parrot(Bird, Pet):
pass
b = Parrot()
b.info()
羽毛
3)重写父类方法
class Bird:
def fly(self):
print('会飞')
class Ostrich(Bird):
def fly(self):
print('鸵鸟说:我不会飞,我只能在地上跑')
os = Ostrich()
os.fly()
鸵鸟说:我不会飞,我只能在地上跑
4)重写父类方法后调用父类方法
class Bird:
def fly(self):
print('会飞')
class Ostrich(Bird):
def fly(self):
print('鸵鸟说:我不会飞,我只能在地上跑')
def dream(self):
self.fly() # 默认情况下,直接调用 fly 方法,总是调用子类重写之后的方法
print('-'*35)
print('梦见:', end='')
Bird.fly(self) # 类名调用方法:未绑定方法,需要显示传入参数
os = Ostrich()
os.dream()
鸵鸟说:我不会飞,我只能在地上跑
-----------------------------------
梦见:会飞
5)调用父类构造方法
背景:
class Employee:
def __init__(self, salary):
self.salary = salary
class Manager(Employee):
def __init__(self, salary, title):
self.salary = salary
self.title = title
mg = Manager(7000, '项目经理')
print(mg.title, mg.salary)
项目经理 7000
分析:
- 父类(Employee)和子类(Manager)中都有实例变量—salary,重复冗余。
- 当需要更改 salary 时(如涨薪 salary *1.5),需要多处更改。
因此,子类构造器应该直接调用父类构造器以方便后期项目升级。
-
方式一:类名调用父类构造方法(未绑定方法,需要传入参数)
class Employee: def __init__(self, salary): self.salary = salary*1.5 # 更改 class Manager(Employee): def __init__(self, salary, title): Employee.__init__(self, salary) # 类名调用父类构造方法 self.title = title mg = Manager(7000, '项目经理') print(mg.title, mg.salary)
项目经理 10500.0
-
方式二:用 super() 函数调用父类构造方法(不需要传入 self 参数)
class Employee: def __init__(self, salary): self.salary = salary* 1.5 # 更改 class Manager(Employee): def __init__(self, salary, title): super().__init__(salary) # super() 函数调用父类构造方法 self.title = title mg = Manager(7000, '项目经理') print(mg.title, mg.salary)
项目经理 10500.0