class Car(): """一次模拟汽车的简单尝试""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): long_name = str(self.year) + ' ' + self.make + ' ' + self.model return long_name.title() def read_odometer(self): print("This car has " + str(self.odometer_reading) + " miles on it.") def update_odometer(self, mileage): if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back an odometer!") def increment_odometer(self, miles): self.odometer_reading += miles class ElectricCar(Car): """电动汽车的独特之处""" def __init__(self,make,model,year): """ 初始化父类的属性,再初始化电动汽车特有的属性 """ super().__init__(make,model,year) self.battery_size = 70 def fill_gas_tank(): """电动汽车没有油箱""" print("This car doesn't need a gas tank!") def describe_battery(self): """打印一条描述电瓶容量的消息""" print("This car has a " + str(self.battery_size) + "-KWh battery.") my_tesla = ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name()) my_tesla.describe_battery() my_tesla.fill_gas_tank()
时间: 2024-01-12 12:04:59 浏览: 181
Python RuntimeError: thread.__init__() not called解决方法
这段代码存在两个问题:
1. 在ElectricCar类中的fill_gas_tank()方法中,缺少self参数。应该将方法定义修改为:`def fill_gas_tank(self):`
2. 最后两行代码的缩进存在问题。应该将它们缩进到与类定义相同的层级。
以下是修改后的代码:
```
class Car():
"""一次模拟汽车的简单尝试"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
class ElectricCar(Car):
"""电动汽车的独特之处"""
def __init__(self,make,model,year):
"""初始化父类的属性,再初始化电动汽车特有的属性"""
super().__init__(make,model,year)
self.battery_size = 70
def fill_gas_tank(self):
"""电动汽车没有油箱"""
print("This car doesn't need a gas tank!")
def describe_battery(self):
"""打印一条描述电瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-KWh battery.")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
my_tesla.fill_gas_tank()
```
阅读全文