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類的繼承的先後順序
# 繼承順序是找父類,父類沒有就找父類的父類,以此類推
3 Python的自省機制
利用自省的函數方法,在程序運行時得知對象的類型,判斷對象是否存在某個屬性,訪問對象的屬性。
dir(), # 返回一個列表(子類繼承相關)
type(), # 判斷變量的數據類型
hasattr(), # 判斷對象是否包含對應的屬性
isinstance() # 判斷變量/類是否正確或者存在繼承關係