我有一個對象定義和使用自定義對象的列表
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
只給出z性愛? (當它似乎正確填寫方法createPriceList()
)
我預計所有的價格都是一樣的,但我不希望所有的價格都是零,而是一些隨機價值。 – 2011-12-14 14:40:40
我更喜歡'price = 0.0`而不是`price = float(0)` – juliomalegria 2011-12-14 14:47:47
@ Marnach,事實上,我放了random(),但這是一個錯誤的想法。 function_giving_a_price()爲最後10輛汽車返回0.0。我修改了我原來的問題 – user1097922 2011-12-14 15:34:40