2011-11-04 86 views
1

我已經創建了一個對象類型..並初始化後,我把它推入列表。 但由於某種原因,行爲並不如預期。 讓我把示例代碼..然後輸出。蟒蛇追加奇怪的行爲

def allignDatesToWhenWasItemSold(pilotInstance): 
    unitsSoldPerDay = pilotInstance._units_sold_per_day 
    productPart = pilotInstance._product 
    date = productPart._date 
    quantity = pilotInstance._product._quantity 

    listOfPilotInstance = [] 
    for i in range(len(unitsSoldPerDay)): 
     perDayQuantity = unitsSoldPerDay[i] 
     #modDate = date 
     #print perDayQuantity 
     modDate = modifyDate(date, i) 
     productPart._date = modDate 

     #print "pro ", productPart._date 
     newPilotInstance = PilotTest(productPart, pilotInstance._name,perDayQuantity) 
     print "here ",newPilotInstance._product._date._date, ' ',newPilotInstance._product._date._month, ' ', newPilotInstance._units_sold_per_day 
     #newPilotInstance.setDate(modDate) 

     listOfPilotInstance.append(newPilotInstance) #note this line.. this is where the trouble is 
     for k in listOfPilotInstance: 
      print k._product._date._date 

    for ele in listOfPilotInstance: 
     print "there " ,ele._product._date._date, ' ',ele._product._date._month, ' ',ele._units_sold_per_day 
    return listOfPilotInstance 

的出認沽表現如下

here 30 7 1 
30 
here 31 7 0 
31<--- now this shouldnt be like this.. as I am doing append.. teh first ele shoulnt be overwrited?? 
31 
here 1 8 2 
1 
1 
1 
there 1 8 1 
there 1 8 0 
there 1 8 2 

所以我的查詢是因爲我做了追加..爲什麼日期元素越來越overwrited? 任何線索,因爲我在做什麼錯了? 感謝

+0

注:'對於我,perDayQuantity枚舉(unitsSoldPerDay):'是更pythonic。 – nmichaels

回答

2

您使用的是相同的productpart實例,只是變異它:

productPart._date = modDate 

由於所有PilotTest對象都有一個參考同productPart例如,所有的人都看到了突變。

您需要在循環的每次迭代中創建類的新實例,並將此新實例分配給productPart

productPart = ...something here... 
+0

那麼在for循環中?像productPart = pilotInstance._product ??? – Fraz

+0

@Fraz:不,那還不是一個*新的*實例。你仍然只是重複使用同一個實例。 –

+0

哦,明白了。 :)非常感謝謝謝.. :) – Fraz