so let's say there is a class A
and I can create instances of class A as follow
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.
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:
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:
instances = {}
for x in range('number of instances'):
instances['inst' + str(x)] = A()
with dict comprehension (recommended):
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.