【问题标题】:local variable 'vehicle' referenced before assignment error encountered even though I assigned a list to the variable 'vehicle' just before that?在遇到分配错误之前引用了局部变量“车辆”,即使我在那之前为变量“车辆”分配了一个列表?
【发布时间】:2021-06-19 02:34:33
【问题描述】:

我的这段代码遇到了错误:在赋值之前引用了局部变量“车辆”。但是当我查看下面的代码时,我已经在 ifelif 语句中为车辆变量分配了一个列表,然后将“车辆”附加到车辆列表中。这里可能出了什么问题?

def populate_vehicles(self, vehicle_file):

  empty_str = ''

  vehicle_str = vehicle_file.readline()
  vehicle_info = vehicle_str.rstrip().split(',')
  file_header_found = vehicle_info
  vehicle_str = vehicle_file.readline()

  while vehicle_str != empty_str:
      vehicle_info = vehicle_str.rstrip().split(',')
      if vehicle_str == '#CARS#' or vehicle_str == '#VANS#' or vehicle_str == '#TRUCKS#':
          file_header_found = vehicle_str

      else:
          if file_header_found == '#CARS#':
              vehicle = Car(*vehicle_info)


          elif file_header_found == '#VANS#':
              vehicle = Van(*vehicle_info)    

          elif file_header_found == '#TRUCKS#':
              vehicle = Truck(*vehicle_info)

      self.vehicles.add_vehicle(vehicle)

      vehicle_str = vehicle_file.readline()

【问题讨论】:

  • 可能没有一个if...elif 语句评估为True,然后您在引用它的地方执行self.vehicles.add_vehicle(vehicle)。尝试print(file_header_found) 并检查输出是什么
  • else: 链中没有if/elif。如果header_found 与您比较的三个字符串中的任何一个都不匹配,那么vehicle 将是未定义的,正如Python 告诉您的那样。所以,添加一个else:,并为vehicle 分配一些东西(或者,给出一个错误)。

标签: python local-variables


【解决方案1】:

如果您输入if,则不会设置车辆。

在这种情况下,当您在倒数第二行引用车辆时,它不会被实例化。

【讨论】:

    猜你喜欢
    • 2020-09-22
    • 2015-05-18
    • 2020-07-29
    • 1970-01-01
    • 2016-10-04
    • 2020-10-02
    • 1970-01-01
    • 2019-06-06
    • 2020-08-13
    相关资源
    最近更新 更多