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

Python : list : the last appended object element replaces all other elements

我有这个功能可以列出一个系统的所有 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

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

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

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

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