2011-11-04 8 views
1

나는 객체 유형을 만들었습니다 .. 그리고 initilializing 후 나는 그것을 목록으로 밀어 넣을 것입니다. 하지만 어떤 이유로 동작이 예상 한 것과 다릅니다. 샘플 코드를 넣은 다음 출력을 보겠습니다.파이썬 추가 이상한 행동

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 

다음과 같다 그래서 내 쿼리 내가 APPEND를하고있는 중이 야하기 때문에 .. 왜 날짜 요소가 overwrited지고 있다는 점이다? 내가 뭘 잘못하고있는 것처럼 단서가 있습니까? 감사

+0

메모 :'for i, perDayQuantity in enumerate (unitsSoldPerDay) :'는 더 pythonic입니다. – nmichaels

답변

2

같은 productpart 인스턴스를 사용하고, 그냥 돌연변이되어 모든 PilotTest 오브젝트가 같은 productPart 인스턴스에 대한 참조, 모두

productPart._date = modDate 

때문에 돌연변이를 참조하십시오.

루프를 통해 반복 할 때마다 클래스의 새 인스턴스를 만들고이 새 인스턴스를 productPart에 할당해야합니다.

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

그래서 for 루프 안에 ?? productPart = pilotInstance._product와 같은 것 ??? – Fraz

+0

@Fraz : 아니요. 아직 새 * 인스턴스가 아닙니다. 당신은 여전히 ​​같은 인스턴스를 재사용하고 있습니다. –

+0

오, 알았어. :) 고마워, 고마워. :) – Fraz