定义和访问自定义对象列表 [英] defining and accessing a list of custom objects

查看:91
本文介绍了定义和访问自定义对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象

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()中似乎正确填充时)
  • Why in showPriceList(), self.carList is correctly recognized (len gives the correct number in looping) but self.carList[i].price gives only zeros? (when it seems correctly filled in method createPriceList())

推荐答案

最可能的解释是,您实际上没有在调用showPriceList()之前先调用createPriceList(). [ edit :既然您已经编辑了问题中的代码,我们就可以消除这种可能性]

The most likely explanation is that you don't actually call createPriceList() before calling showPriceList(). [edit: now that you've edited the code in your question, we can eliminate this possibility]

此外,createPriceList()发生错误,即您将对同一Car对象的引用分配给列表的所有元素.当且仅当最后一个 random() function_giving_a_value()调用返回零时,此错误才能解释该行为.

Also, createPriceList() has an error whereby you assign references to the same Car object to all elements of the list. This error could also explain the behaviour, if and only if the last random() function_giving_a_value() call returns zero.

最后,您在几个地方缺少self. [编辑:再次,您似乎在最近的编辑中已经修复了其中的一些问题.

Finally, you're missing self. in a couple of places [edit: again, you seem to have fixed some of these in a recent edit].

这是我的写法:

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()

这篇关于定义和访问自定义对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆