1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| title = "类的继承" print(f"------------ {title} -------------------")
class Car: """ 汽车 """
def __init__(self, brand, type, price): self.brand = brand self.type = type self.price = price
def info(self): print("Brand:", self.brand, "Type:", self.type, "Price:", self.price) def drive(self): print("The Car is running ...")
class BMW(Car): """ 宝马汽车 """
def __init__(self, type, price, support_electric): super().__init__("宝马", type, price) self.support_electric = support_electric
def can_use_electric(self): if self.support_electric : print("本车支持电动") else: print("本车不支持电动")
def drive(self): print("宝马在狂飙中...")
my_bmw = BMW("SUV", 1111, True)
print("\n调用父类方法") my_bmw.info()
print("\n调用子类方法") my_bmw.can_use_electric() my_bmw.drive()
print("\n访问父类的属性") print("My BMW Price is", my_bmw.price)
print("\n访问子类的属性") print("My BMW support electric:", my_bmw.support_electric)
print("\n子类判断") print("BMW 是否为 Car 的子类", issubclass(BMW, Car) ) print("BMW 是否为 BMW 的子类", issubclass(BMW, BMW) )
print("\n类型判断") print("变量 my_bmw 是否为 Car 类型 ", isinstance(my_bmw, Car) ) print("变量 my_bmw 是否为 BMW 类型 ", isinstance(my_bmw, BMW) )
print("\n通过特殊属性 __bases__ 获取其基类信息") print("Car类的基类:", Car.__bases__) print("BMW类的基类:", BMW.__bases__)
|