【发布时间】:2021-02-20 22:56:58
【问题描述】:
我是 Python 新手,需要创建一个包含多个数据类实例的列表。我尝试使用列表乘法来执行此操作,因为我认为它会更快,因为我必须“附加”我的数据类的数千个单独实例。但是,我的列表乘法似乎创建的对象都引用了我的数据类的同一个实例,而不是我的数据类的多个独立实例。
这是我尝试过的简单示例:
class Test: # define data class "Test".
def __init__(self, a):
self.a = a
test = Test(1) # define an instance of data class "Test".
tests = [test] * 2 # define a list called "tests", with 2 instances of "test".
print(tests[0].a) # both instances of 'a' in the list show that "a = 1".
print(tests[1].a)
tests[0].a = 2 # change the first instance of 'a' in the list to "a = 2".
print(tests[0].a) # first instance of 'a' properly changed to "a = 2".
print(tests[1].a) # but, the second instance of 'tests.a' ALSO changed from 1 to 2!
我曾预计更改列表中的一个实例不会影响另一个实例,但看起来我实际上拥有的是同一实例的多个副本。那么,如何创建一个包含我的数据类“Test”的多个独立实例的列表?
【问题讨论】: