Python方法下的条件句

2024-10-03 11:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直得到一个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

Tags: selfoutputmodeldefattributecarcarsyear
2条回答

我发现你的代码有很多问题。你知道吗

首先,我注意到很多对self.X的引用,其中X不是CarInventory的成员。这是对self的误用,它用于将变量限定到解释器应该查找的类(或偶尔的函数)。如果您正在引用self.manufacturer,而CarInventory没有名为manufacturer的成员,那么您将得到一个异常。你知道吗

我还注意到,在add_car函数中,您将整个汽车列表设置为要添加的新车。根据这个方法的定义,我认为这不是你想要的。相反,您应该使用append方法将新车添加到您的汽车列表中。你知道吗

compare也有一些问题。首先,您试图在某个名为highest的变量中apss,而不是'highest'的参数的字符串direction,这就是您的NameError的来源。您还遇到了一些比较问题和缺少的else。你知道吗

我已经修好了你的密码

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.append({
            'manufacturer': manufacturer, 
            'model': model, 
            'year': year, 
            'mpg': mpg})
        self.n_cars = self.n_cars + 1

    def compare(self, attribute, direction = 'highest'):
        lowest = self.cars[0]
        highest = self.cars[0]
        for car in self.cars:
            if car[attribute] < lowest[attribute]:
                lowest = car
            elif car[attribute] > highest[attribute]:
                highest = car
       if direction == 'highest':
           return highest 
      else:
          return lowest

另外,为了便于阅读,应该在类定义和函数之间添加换行符。你知道吗

highest给出NameError的原因是您编写了:

def compare(self, attribute, direction=highest):

它告诉Python,如果调用方在调用compare方法时不包含第二个参数(direction),那么该方法应该使用名为highest的变量中的任何值。但是在你的程序中没有声明这样的变量。你知道吗

你可能想写:

 def compare(self, attribute, direction='highest'):

它告诉Python如果调用方没有为direction参数提供值,则使用highest文本字符串值。你知道吗

至于CarInventory错误,您没有向我们展示生成该错误的程序部分。它位于您试图使用CarInventory类的地方,而不是您定义它的地方。你知道吗

相关问题 更多 >