Python object-oriented (2)-inheritance (3)

super() calls the parent class

The previous section introduced a complex method of calling the parent class. Now, we will introduce a simple method of calling the parent class. We will change the previous code to multi-layer inheritance, and each class inherits only one parent class.

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()

At this time, the output is bang1, it can be seen that the routine of the super() method is also initialized first, and python will follow the __mro__ order to find the parent class to inherit the corresponding method

Guess you like

Origin blog.csdn.net/weixin_48445640/article/details/108814887