写一个car类Python并且继承
时间: 2024-05-11 10:19:03 浏览: 11
好的,下面是一个简单的 `Car` 类的实现,并继承了 `Vehicle` 类:
```python
class Vehicle:
def __init__(self, make, model, year, weight):
self.make = make
self.model = model
self.year = year
self.weight = weight
def start(self):
print("Starting the vehicle")
def stop(self):
print("Stopping the vehicle")
class Car(Vehicle):
def __init__(self, make, model, year, weight, num_doors):
super().__init__(make, model, year, weight)
self.num_doors = num_doors
def drive(self):
print("Driving the car")
```
在上面的代码中,我们定义了一个 `Vehicle` 类,它有一些属性(制造商、型号、年份和重量)和方法(启动和停止)。然后,我们定义了一个 `Car` 类,它继承了 `Vehicle` 类,并添加了一个新的属性 `num_doors`,表示汽车的门数。此外,`Car` 类还有一个新的方法 `drive()`,表示驾驶汽车。我们使用 `super()` 函数来调用父类 `Vehicle` 的 `__init__()` 方法来初始化继承的属性。