###### 闷声小发财

2019-05-09 10:19 阅读 614

# 请教，关于《Python从入门到实践》第九章 类 中的例子 electric_car一段代码的问题

def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270

``````    message = "This car can go approximately " + str(range)
message += " miles on full charge."
print(message)
``````

def get_range(self, range=240):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270

``````    message = "This car can go approximately " + str(range)
message += " miles on full charge."
print(message)
``````

def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 80:
range = 280
else:
range = 200
message = "This car can go approximately " + str(range)
message += " miles on full charge."
print(message)

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享

#### 2条回答默认 最新

• 已采纳
代码的灵魂是bug！ 2019-05-09 20:16

书上的写法完全没问题，你检查一下你自己的代码，下面是书上的

``````class Car():
def __init__(self,make,model,year):
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
long_name = str(self.year)+' '+self.make+' '+self.model
return long_name.title()
print('This car has '+str(self.odometer_reading)+' miles on it.')
def update_odometer(self,mileage):
if mileage >= self.odometer_reading:
else:
print('You cant roll back an odometer!')
def increment_odometer(self,miles):
class Battery():
def __init__(self,battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print('This car has a '+str(self.battery_size)+'-kWh battery.')
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270

message = "This car can go approximately "+str(range)
message += ' miles on a full charge'
print(message)

class ElectricCar(Car):
def __init__(self,make,model,year):
super().__init__(make,model,year)
self.battery = Battery()

``````
``````from car import ElectricCar

my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()
``````
``````2016 Tesla Model S
This car has a 70-kWh battery.
This car can go approximately 240 miles on a full charge
``````
点赞 评论 复制链接分享
• 502203305 2019-05-09 12:36

首先range是根据if条件进行创建变量。但是在built-in里面有一个range类，那么也就是说，不管你有没有定义range，这个执行都是对的。
只是执行的结果不同而已。最好是贴完整代码好看一些。

点赞 评论 复制链接分享