设计一个汽车类Vehicle,包含的属性有车轮个数wheels和车重weight。小车类Car是Vehicle的子类,其中包含的属性有载人数loader。卡车类Truck是Car类的子类,其中包含的属性有载重量payload。每个类都有构造方法和输出
时间: 2024-02-21 07:00:18 浏览: 220
下面是一个示例代码:
```
class Vehicle:
def __init__(self, wheels, weight):
self.wheels = wheels
self.weight = weight
def output(self):
print("Vehicle has {} wheels and weighs {} kg.".format(self.wheels, self.weight))
class Car(Vehicle):
def __init__(self, wheels, weight, loader):
super().__init__(wheels, weight)
self.loader = loader
def output(self):
print("Car has {} wheels, weighs {} kg, and can carry {} people.".format(self.wheels, self.weight, self.loader))
class Truck(Car):
def __init__(self, wheels, weight, loader, payload):
super().__init__(wheels, weight, loader)
self.payload = payload
def output(self):
print("Truck has {} wheels, weighs {} kg, can carry {} people, and can carry {} kg of payload.".format(self.wheels, self.weight, self.loader, self.payload))
```
这个代码定义了一个 Vehicle 类,一个 Car 类和一个 Truck 类,每个类都有自己的属性和构造方法。每个类都有自己的输出方法 output,用于输出自己的属性。在每个类的构造方法中,使用 super() 调用父类的构造方法来初始化继承的属性。在每个类的 output 方法中,使用格式化字符串来输出自己的属性。
阅读全文