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

单继承

#所有类默认继承object
class Gun(object):
	def __init__(self,width):
		self.length = 100
		self.width = width
	def shoot(self):
		print('bang')
		
class Wuzi(Gun):
	pass

wuzi = Wuzi(3)

wuzi.shoot()
		

如上例所示,Gun称为父类,Wuzi为子类,Wuzi继承Gun,自动继承父类属性及方法,此时Wuzi后面的括号内只写了一个父类,称之为单继承

多继承

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):
	pass

wuzi = Wuzi()

wuzi.shoot()

此时输出为bang1,即:
当一个类继承多个父类,默认使用第一个父类的同名方法和属性

子类重写父类同名属性和方法

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):
		print('bang3')

wuzi = Wuzi()

wuzi.shoot()

此时输出为bang3

猜你喜欢

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