python--多继承

74 阅读1分钟

多继承:

引言:

image.png

image.png

代码如下:

# 定义一个表示房屋的类House
class House(object):
    def live(self):          # 居住
        print("供人居住")
    def test(self):
        print("House类测试")

# 定义一个表示汽车的类Car
class Car(object):
    def drive(self):         # 行驶
        print("行驶")
    def test(self):
        print("Car类测试")

# 定义一个表示房车的类,继承House和Car类
class TouringCar(House, Car):
    pass

tour_car = TouringCar()
tour_car.live()    # 子类对象调用父类House的方法
tour_car.drive()   # 子类对象调用父类Car的方法
tour_car.test()    # 子类对象调用两个父类的同名方法

运行结果如下:

image.png