【问题标题】:Create a Python list with multiple instances of a data class [duplicate]创建一个包含多个数据类实例的 Python 列表 [重复]
【发布时间】: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”的多个独立实例的列表?

【问题讨论】:

    标签: python list class


    【解决方案1】:

    使用列表推导:

    tests = [Test(1) for _ in range(100)]
    

    上面创建了100不同的Test对象。

    【讨论】:

    • 成功了,太好了!它似乎也很快地填充了列表。非常感谢。
    • 我刚刚看到问题 240178“list-of-lists-changes-reflected-across-sublists-unexpectedly”的答案解释了为什么列表乘法不起作用。
    • @DougD。我为此添加了一个链接:stackoverflow.com/questions/240178/…,这样人们就不必复制和粘贴了。
    猜你喜欢
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2015-05-18
    • 2022-01-01
    相关资源
    最近更新 更多