定义和访问自定义对象列表

1 投票
3 回答
11348 浏览
提问于 2025-04-17 08:22

我有一个对象

class Car:
  def __init__(self):
    price = float(0)

然后还有一个

class Day:
  def __init__(self):
    self.carList = [Car() for each in range(100)]
    self.createPriceList()

  def createPriceList(self):
    tempCar = Car()
    for i in range(100):
      tempCar.price = function_giving_a_value() # 10 last cars have 0.0 as value
      self.carList[i] = tempCar
      print i, self.carList[i].price 
# prints the correct list : each line contains a correct price
#edited after answers : in fact it's just misleading, cf answers

  def showPriceList(self):
    for i in range(len(self.carList)):
      print i, self.carList[i].price 
# prints i (correct) but each self.carList[i].price as 0.0
# so len(self.carList) gives correct value, 
# but self.carList[i].price a wrong result

我的问题是:

  • 为什么在 showPriceList() 这个方法里,self.carList 能正确识别(用 len 计算出来的数量是对的),但是 self.carList[i].price 却只显示零?(看起来在 createPriceList() 方法里是填充正确的)

3 个回答

0

根据你想要实现的目标,可能更好的是为每一个单独的汽车(Car())保留单独的属性,然后在类外面建立一个汽车实例的列表:

import random

class Car:
    def __init__(self):
        self.price = random.random()

class Day:
    def __init__(self):
        self.cars = [Car() for each in range(100)]

day = Day()
priceList = [car.price for car in day.cars]

我认为价格列表(priceList)不应该放在类里面,因为这样是多余的。

0

首先,你在使用for循环时有点“错误”。你是先根据列表的长度创建一个索引,然后再用这个索引去访问同一个列表里的元素。其实可以更简单,比如你的createPriceList方法,可以这样写:

def createPriceList(self):
    for car in self.carList
        car.price = random()
        print car.price

在你的例子中,你是在循环之前创建了一辆车,然后每次存储这辆车时都在改变它的值。这就意味着你的车列表里其实都是指向同一辆车的引用,所以它们的价格都会是一样的。

那些零是因为random()函数返回的是一个0到1之间的小数。如果这个小数小于0.1,打印出来的就会显示为0.0。

4

最有可能的原因是,你在调用 showPriceList() 之前并没有真正调用 createPriceList()

另外,createPriceList() 里有个错误,就是你把同一个 Car 对象的引用赋给了列表中的所有元素。如果最后一次调用的 random()function_giving_a_value() 返回的是零,这个错误也可能会导致你看到的行为。

最后,你在几个地方缺少了 self. [编辑: 看起来你最近的修改中修复了一些这些问题]。

以下是我会写的代码:

import random

class Car:

    def __init__(self, price):
        self.price = price

class Day:

  def __init__(self, n):
      self.carList = []
      for i in range(n): # could also use list comprehension here
          self.carList.append(Car(random.random()))

  def printPriceList(self):
      for i, car in enumerate(self.carList):
        print(i, car.price)

day = Day(20)
day.printPriceList()

撰写回答