我有这个函数来列出一个系统的所有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
应打印以下内容:
^{pr2}$而输出是
ACPI Lid
ACPI Lid
ACPI Lid
ACPI Lid
如您所见,它复制了所有对象的最后一个对象。我得到的前一个输出是在append
语句之后打印deviceList[-1].ProductName
,因此添加的对象是正确的。但是,一旦我退出第一个循环并进入第二个(打印)循环,对象就被复制了。在
这是因为列表中的所有元素都引用同一个对象x。它们具有上一次迭代的值,因为它是一个可变对象,所以每次执行
x.ProductName = J.__getattr__('ProductName')
时,都要更改列表中引用的同一对象的产品名。将列表视为包含指向同一对象的指针的列表。在您需要做的是在循环的每次迭代中定义一个用户定义类的新对象,例如:
y = UserDefinedClass(x) y.ProductName = J.__getattr__('ProductName') deviceList.append(y)
相关问题 更多 >
编程相关推荐