欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

批量生成对象

程序员文章站 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都是创建出的对象
相关标签: python python