批量生成对象
程序员文章站
2022-04-18 13:57:22
...
exec() + string.format()
class testclass():
def __init__(self):
print("obj is created!")
self.num=1
exec('var{} = {}'.format(i, i))
exec("obj{}=testclass()".format("demo"))
print(objdemo.num)
===============
output:
1
class testclass():
def __init__(self):
print("obj is created!")
self.num=1
exec("aa=testclass()")
print(type(aa))
print(aa.num)
===============
output:
obj is created!
<class '__main__.testclass'>
1
locals()
class A():
def __init__(self):
self.val = 10
for i in range(10):
locals()[f'x{i}'] = A()
==========================
x1,x2...x10都是创建出的对象