python面向对象(2)—— 继承(3)

super()调用父类

上一节介绍了一种复杂的调用父类的方法,现在介绍一种简便的调用父类方法,我们将以前的代码改为多层继承,并且每一个类都只继承一个父类。

class Gun(object):
	def __init__(self):
		self.length = 100
		
	def shoot(self):
		print('bang1')
		
class Wuzi(Gun):
	def shoot(self):
		# 注意这里要先初始化自己,这样可以避免调用父类方法后再调用自己的方法时,还是父类的方法输出
		super().__init__()
		super().shoot()
		
	
class XiaoWuzi(Wuzi):
	def shoot(self):
		super().__init__()
		super().shoot()

wuzi = XiaoWuzi()

wuzi.shoot()

此时输出为bang1,可见super()方法的套路也是先初始化,python会遵循__mro__顺序依次找父类继承相应的方法

猜你喜欢

转载自blog.csdn.net/weixin_48445640/article/details/108814887