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

在上一节中,我们重写了父类的方法,但是如果我们还想用这两个父类的方法,可按如下例子进行重写:

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

wuzi = Wuzi()

wuzi.shoot()
wuzi.shoot1()
wuzi.shoot2()

此时输出为bang3,bang1,bang2

多层继承

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

class XiaoWuzi(Wuzi):
	pass

wuzi = XiaoWuzi()

wuzi.shoot()
wuzi.shoot1()
wuzi.shoot2()

像XiaoWuzi这种继承了Wuzi(又继承自两个父类)这样的形式称为多层继承,它照样可以用最高父类(Gun1、Gun2)的方法

猜你喜欢

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