简体   繁体   English

在 Python 中创建 class 的多个实例

[英]creating multiple instances of a class in Python

so let's say there is a class A所以假设有一个 class A

and I can create instances of class A as follow我可以创建 class A 的实例如下

inst1 = A()

inst2 = A()

inst3 = A()
...

Can I do this job more neatly?我可以更整洁地完成这项工作吗?

I have to create the instances as many as a certain number that is given by a server (the number can vary every time).我必须创建与服务器给出的一定数量一样多的实例(数量每次都可能不同)。

I'm expecting to do something like我期待做类似的事情

for NUM in range(2):
    inst + NUM = A()

then the instances I want to get as a result would be three instances (inst0, inst1, inst2) that are class A.那么我想要获得的实例将是三个实例(inst0、inst1、inst2),它们是 class A。

Thank you in advance先感谢您

you can't create single variable if you don't assign them a specified name, for creating unknow amount of variables use lists (inndexed) or dictionarys (named):如果您不为它们分配指定的名称,则无法创建单个变量,用于创建未知数量的变量使用列表(索引)或字典(命名):

Lists列表

with for loops:使用 for 循环:

instances = []

for x in range('number of instances'):

    instances.append(A())

with list comprehension (recommended):使用列表理解(推荐):

instances = [A() for x in range('number of instances')]

Dictionarys字典

with for loops:使用 for 循环:

instances = {}

for x in range('number of instances'):

    instances['inst' + str(x)] = A()

with dict comprehension (recommended):使用 dict 理解(推荐):

instances = {'inst' + str(x): A() for x in range('number of instances')}

use a dictionary or list to create your variable使用字典或列表创建变量

dictionary字典

d={}
for x in range(1, 10):
    d[f"inst{x}"] = A()

list列表

inst=[]
for i in range(10):
    inst.append(A())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM