多维类列表-覆盖问题 [英] Multidimensional list of classes - overwriting issue

查看:30
本文介绍了多维类列表-覆盖问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个类列表,但是每次更改列表中的一个元素时,列表中的所有类元素都会被覆盖:

I want to create a list of classes, but every time I change an element in the list, all class elements in the list are overwritten:

class TypeTest:
    def __init__(self):
    self.val = int()

data = list([TypeTest for _ in range(3)])

for i in range(3):
    data[i].val = i
    print([data[0].val, data[1].val, data[2].val])

最后,我需要一个多维数组,并且将有一个更复杂的类,但是问题是相同的.

At the end, I need a multidimensional array and will have a more complex class, but the issue is the same.

推荐答案

TypeTest 是一种类型; TypeTest()创建该类型的实例.您需要

TypeTest is a type; TypeTest() creates an instance of that type. You need

data = list([TypeTest() for _ in range(3)])

代替

data = list([TypeTest for _ in range(3)])

在后一种情况下,您只是将同一 TypeTest 的多个副本添加到列表中.

In the latter case, you are just adding multiple copies of the same TypeTest to the list.

实际上,如果打印列表元素的内存地址,则会发现它们是同一对象:

Indeed, if you print the memory address of your list elements, you will find that they're the same object:

>>> data = list([TypeTest for _ in range(3)])
>>> print([id(x) for x in data])
[140184769568224, 140184769568224, 140184769568224]

>>> data = list([TypeTest() for _ in range(3)])
>>> print([id(x) for x in data])
[4451998096, 4451996816, 4451996176]

这篇关于多维类列表-覆盖问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆