Skip to main content
 首页 » 编程设计

Python 速成类(class)之第 9 章 my_electric_car之get_range() 的问题

2024年12月31日7TianFang

我正在阅读 Python 速成类(class)这本书,但我一直停留在书中给出的示例上。我什至复制-粘贴了书中的脚本,但仍然出现错误。

名为 car.py 的文件

"""A class that can be used to represent a car.""" 
 
class Car(): 
"""A simple attempt to represent a car.""" 
 
def __init__(self, make, model, year): 
    """Initialize attributes to describe a car.""" 
    self.make = make 
    self.model = model 
    self.year = year 
    self.odometer_reading = 20 
 
def get_descriptive_name(self): 
    """Return a neatly formatted descriptive name.""" 
    long_name = str(self.year) + " " + self.make +\ 
                " " + self.model 
    return long_name.title() 
 
def read_odometer(self): 
    """Print a statement showing the car's mileage""" 
    print("This car has " + str(self.odometer_reading) + 
          " miles on it.") 
 
def update_odometer(self, mileage): 
    """ 
    Set the odometer reading to the given value. 
    Reject the change if it attempts to roll the odometer back. 
    """ 
    if mileage >= self.odometer_reading: 
        self.odometer_reading = mileage 
    else: 
        print("You can't roll back an odometer!") 
 
def increment_odometer(self, miles): 
    """Add the given amount to the odometer reading.""" 
    self.odometer_reading += miles 
 
class Battery(): 
"""A simple attempt to model a battery for an electric car.""" 
 
def __init__(self, battery_size=60): 
    """Initialize the battery's attributes.""" 
    self.battery_size = battery_size 
 
def describe_battery(self): 
    """Print a statement describing the battery size.""" 
    print("This car has a " + str(self.battery_size) + "-kWh battery.") 
 
def get_range(self): 
    """Print a statement about the range this battery provides.""" 
    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): 
"""Models aspects of a car, specific to electric vehicles.""" 
 
def __init__(self, make, model, year): 
    """ 
    Initialize attributes of the parent class. 
    Then initialize attributes specific to an electric car. 
    """ 
    super().__init__(make, model, year) 
    self.battery = Battery() 

现在,当我尝试通过以下脚本(在文件 my_electric_car.py 中)导入类时:

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() 

不幸的是我得到了一个错误:

/usr/local/bin/python3.7 "/Users/XXX/Desktop/Python Crash Course/Chapter 9/my_electric_car.py" 
2016 Tesla Model S 
This car has a 60-kWh battery. 
Traceback (most recent call last): 
File "/Users/bielas/Desktop/Python Crash Course/Chapter 9/my_electric_car.py", line 7, in <module> 
my_tesla.battery.get_range() 
File "/Users/bielas/Desktop/Python Crash Course/Chapter 9/car.py", line       56, in get_range 
message = "This car can go approximately " + str(range) 
UnboundLocalError: local variable 'range' referenced before assignment 
 
Process finished with exit code 1 

请您参考如下方法:

您的电池的初始化 self.battery_size 为 60。

如果不将其更改为 70 或 85,range 会得到什么值?

def get_range(self): 
    """Print a statement about the range this battery provides.""" 
    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) 

(citation of your code)

更改为:

     if self.battery_size == 70: 
         range = 240 
     elif self.battery_size == 85: 
         range = 270 
     else:  
         # chose a fitting value for 60 - or better: use a formular to calc range   
         # so you do not have to provide hardcoded range values for all charges 
         # between 0 and 2000 
         range = 200 # or smth like: range = self.battery_size // 3 

旁注:

避免使用 python 已经使用的名称,这包括 f.e.内置函数(最小值、最大值、范围、列表、集合、字典...)built-ins Link .您变量将此名称从函数重新分配给您的值,并隐藏它们 - 因此不能再使用它们。