我一直得到一个NameError
声明CarInventory
没有定义,也是最高的。另外,我仍然不确定compare()方法的代码是否正确。你知道吗
这是我的作业代码:
class CarInventory():
def __init__(self, n_cars = 0, cars = []):
self.n_cars = n_cars
self.cars = cars
def add_car(manufacturer,model,year,mpg):
self.cars = {'manufacturer': self.manufacturer, 'model': self.model, 'year': self.year, 'mpg': self.mpg}
self.n_cars = self.n_cars + 1
def compare(self, attribute, direction=highest):
self.lowest = self.cars[0]
self.direction = self.cars[0]
for car in self.cars:
if self.car[attribute] < self.lowest:
self.lowest = car
elif self.car[attribute] > self.highest:
self.highest = car
if direction == highest:
output = highest
elif direction == lowest:
output = lowest
return output
我发现你的代码有很多问题。你知道吗
首先,我注意到很多对
self.X
的引用,其中X
不是CarInventory
的成员。这是对self
的误用,它用于将变量限定到解释器应该查找的类(或偶尔的函数)。如果您正在引用self.manufacturer
,而CarInventory
没有名为manufacturer
的成员,那么您将得到一个异常。你知道吗我还注意到,在
add_car
函数中,您将整个汽车列表设置为要添加的新车。根据这个方法的定义,我认为这不是你想要的。相反,您应该使用append
方法将新车添加到您的汽车列表中。你知道吗compare
也有一些问题。首先,您试图在某个名为highest
的变量中apss,而不是'highest'
的参数的字符串direction
,这就是您的NameError
的来源。您还遇到了一些比较问题和缺少的else
。你知道吗我已经修好了你的密码
另外,为了便于阅读,应该在类定义和函数之间添加换行符。你知道吗
highest
给出NameError的原因是您编写了:它告诉Python,如果调用方在调用
compare
方法时不包含第二个参数(direction),那么该方法应该使用名为highest
的变量中的任何值。但是在你的程序中没有声明这样的变量。你知道吗你可能想写:
它告诉Python如果调用方没有为
direction
参数提供值,则使用highest
的文本字符串值。你知道吗至于
CarInventory
错误,您没有向我们展示生成该错误的程序部分。它位于您试图使用CarInventory
类的地方,而不是您定义它的地方。你知道吗相关问题 更多 >
编程相关推荐