Python速成班-第9章my_electric_car-get_range()问题

时间:2018-08-30 05:37:45

标签: python python-3.x

我正在学习《 Python崩溃课程》这本书,并且只限于书中给出的示例。我什至复制-从书中粘贴了脚本,仍然出现错误。

名为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

1 个答案:

答案 0 :(得分:1)

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

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

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)
     

(引用您的代码)

更改为:

     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。内置(最小,最大,范围,列表,集合,字典,...)built-ins Link 。您将变量从函数中重新分配了该名称,然后将其阴影化-因此无法再使用它们。