python问题class Car: num_wheels = 4 gas = 30 def __init__(self, make, model): self.make = make self.model = model self.color = 'No color yet. You need to paint me.' self.wheels = Car.num_wheels self.gas = Car.gas def paint(self, color): self.color = color return self.make + ' ' + self.model + ' is now ' + color def drive(self): if self.wheels < Car.num_wheels or self.gas <= 0: return 'Cannot drive!' self.gas -= 10 return self.make + ' ' + self.model + ' goes vroom!' def pop_tire(self): if self.wheels > 0: self.wheels -= 1 def fill_gas(self): self.gas += 20 return 'Gas level: ' + str(self.gas) class MonsterTruck(Car): """ >>> deneros_car = Car('Tesla', 'Model S') >>> deneros_truck = MonsterTruck('Monster', 'Batmobile') >>> deneros_car.size 'Tiny' >>> deneros_car.drive() 'Tesla Model S goes vroom!' >>> deneros_truck.size 'Monster' >>> deneros_truck.drive() Vroom! This Monster Truck is huge! 'Monster Batmobile goes vroom!' >>> MonsterTruck.drive(deneros_truck) Vroom! This Monster Truck is huge! 'Monster Batmobile goes vroom!' >>> Car.drive(deneros_truck) 'Monster Batmobile goes vroom!' >>> deneros_truck.gas 0 >>> MonsterTruck.rev(deneros_truck) Vroom! This Monster Truck is huge! >>> MonsterTruck.rev(deneros_car) Vroom! This Monster Truck is huge! """ import doctest doctest.testmod()
时间: 2023-06-26 22:03:22 浏览: 170
Python库 | pyaudio_wheels-0.0.1-cp35-cp35m-manylinux1_i686.whl
5星 · 资源好评率100%
这段代码定义了两个类:Car和MonsterTruck。MonsterTruck是Car的子类,它继承了Car的属性和方法。
在Car类中,定义了四个方法:__init__、paint、drive和fill_gas。__init__是构造函数,它初始化Car对象的属性;paint用来给汽车涂上颜色;drive用来驾驶汽车;fill_gas用来加油。
在MonsterTruck类中,没有重新定义任何方法,它继承了Car类的所有方法和属性。但是它有一个新的属性size,用来表示怪兽卡车的大小。
在测试代码中,首先创建了一个Car对象deneros_car和一个MonsterTruck对象deneros_truck。然后测试了一些方法,包括drive和rev。注意到在测试中,有些方法是通过Car类和MonsterTruck类来调用的,这说明了继承的作用。
阅读全文