python 的继承重写和 super函数

1 super函数实现父类方法的继承和重写

class Car1:   
	def __init__(self, color, weight):  
		self.color = color
		self.wheel = 4
		self.weight = weight
		self.speed = 0
		
	def run_up(self, arg):   # 父类中的run_up方法
		self.speed += arg
		print("汽车加速了,速度:", self.speed)		
		
	def run_down(self, arg):
		self.speed -= arg
		print("汽车减速了,速度:", self.speed)		
		
	def stop(self):
		self.speed = 0
		print("汽车停下来了")	
		
		
class Car2(Car1):
	def __init__(self, sign, type, air):
		self.sign = sign
		self.type = type
		self.car_air = air
	# 子类重写run_up方法
	def run_up(self, *arges, **kwargs):   #覆盖
		Car1.speed = 0
		super().run_up(*arges, **kwargs)
		# print("车辆牌子是{},型号是{},空调系统是{}".format(self.sign, self.type, self.car_air))		
	def run_down(self):   #覆盖
		print("车辆牌子是{},型号是{},空调系统是{}".format(self.sign, self.type, self.car_air))
		
		
taxi = Car1("red", weight=100)
taxi.run_up(20)
taxi.run_down(10)
taxi.stop()

aodi = Car2(sign="aodi", type="f103", air="357a159")

aodi.run_up(30)
aodi.run_down()
aodi.stop()

运行结果
运行结果

2 继承的顺序__mro__

class A:
    def __init__(self):
        print("A")


class B(A):
    def __init__(self):
        print("B")
        super().__init__()


class C(A):
    def __init__(self):
        print("C")
        super().__init__()


class D(B, C):
    def __init__(self):
        print("D")
        super().__init__()


if __name__ == '__main__':
    d = D()     # D  B C A Object  继承顺序遵循C3算法(Python3)
    print(D.__mro__)  # 打印出D类的继承的先后顺序
	# 继承顺序是找父类,父类没有就找父类的父类,以此类推

参考他人博客解析C3算法

3 Python的自省机制

利用自省的函数方法,在程序运行时得知对象的类型,判断对象是否存在某个属性,访问对象的属性。

dir(), # 返回一个列表(子类继承相关)
type(), # 判断变量的数据类型
hasattr(), # 判断对象是否包含对应的属性
isinstance() # 判断变量/类是否正确或者存在继承关系

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章