我正在阅读Python Crash Course这本书,我坚持在书中给出的例子。我甚至复制 - 粘贴书中的脚本仍然出错。
文件名为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)
(引用你的代码)
改成:
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.内置插件(min,max,range,list,set,dict,...)built-ins Link 。你变量将这个名称从函数重新分配给你的值并且你将它们遮蔽 - 因此不能再使用它们了。