python - 创建一个包含多个数据类实例的 Python 列表
问题描述
我是 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”的多个独立实例的列表?
解决方案
使用列表推导:
tests = [Test(1) for _ in range(100)]
以上创建了100
不同的Test
对象。
推荐阅读
- c - 使用 c 中函数的 int 值定义数组大小
- vue.js - vue-cli 不创建文件夹结构
- php - 如何在 drupal 8 中通过 uri 加载图像?
- javascript - 当我使用 axios/vue js 发布到 php 时,Javascript .value 为空
- java - IBM Watson 语音到文本的依赖关系
- c# - 如何在剃刀中使模型更改为全局
- javafx - 透视滚动文本(选取器 iOS 样式)
- magento - XML 类别更新被忽略 + Manadev 过滤器问题 - Magento 1.9 Lesti FPC 1.4.8
- r - 为什么 Rcpp 仅在从 R 包调用时才起作用,而不是在直接通过 sourceCpp 获取时才起作用?
- ruby-on-rails - 在 Rails 中删除时发出警报