Python:list:最后添加的对象元素替换所有其他元素

时间:2015-11-30 14:27:28

标签: python list append

我有这个功能列出系统的所有PNP设备。问题是,即使查询和附加对象是完美的,附加对象的列表也只复制最后一个对象的整个列表。

def getnicinfo():
    c = wmi.WMI()
    wql = "SELECT * FROM Win32_NetworkAdapter WHERE PhysicalAdapter=true AND Manufacturer != 'Microsoft' AND NOT PNPDeviceID LIKE 'ROOT\\%'"
    temp = c.query(wql)
    x = data.device() //user-defined class, does not really matter as the data exchanged is compatible

    deviceList = list()
    print("\nreturns physical NIC")
    for J in temp:
        x.ProductName = J.__getattr__('ProductName')
        deviceList.append(x)
    for i in deviceList:    // this is where the last element that was added in last loop replaces every other element
        print(i.ProductName) 
return deviceList

这应该打印以下内容:

Intel(R) HD Graphics Family
Intel(R) 8 Series USB Enhanced Host Controller #1 - 9C26
Generic USB Hub
ACPI Lid

而输出是

ACPI Lid
ACPI Lid
ACPI Lid
ACPI Lid

如您所见,它会复制所有对象的最后一个对象。我得到的上一个输出是在deviceList[-1].ProductName语句之后打印append,因此添加的对象是正确的。但是,只要我退出第一个循环并进入第二个(打印)循环,就会复制对象。

1 个答案:

答案 0 :(得分:1)

这是因为列表中的所有元素都引用了相同的对象x。它们具有最后一次迭代的值,因为它是一个可变对象,因此每次执行x.ProductName = J.__getattr__('ProductName')时,都会更改列表中引用N次的同一对象的ProductName。将列表视为包含指向同一对象的指针的列表。

您需要做的是在循环的每次迭代中定义用户定义类的新对象,如:

y = UserDefinedClass(x) y.ProductName = J.__getattr__('ProductName') deviceList.append(y)

相关问题