python附加怪异行为

2024-10-03 17:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经创建了一个对象类型。。在初始化之后,我把它放到了一个列表中。 但由于某些原因,这种行为并不像预期的那样。 让我输入示例代码。。然后是输出。你知道吗

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

所以我的问题是,既然我在做附加。。为什么日期元素会被覆盖? 关于我做错了什么有什么线索吗? 谢谢


Tags: datehereproductthisthereunitsprintsold
1条回答
网友
1楼 · 发布于 2024-10-03 17:28:27

您使用的是同一个productpart实例,只是对其进行了修改:

productPart._date = modDate

因为所有的PilotTest对象都引用了相同的productPart实例,所以它们中的所有对象都看到了突变。你知道吗

您需要在循环的每次迭代中创建类的新实例,并将这个新实例分配给productPart。你知道吗

productPart = ...something here...

相关问题 更多 >