使用compile和exec方法,可以达到你的要求,代码参考如下
class Test(object):
def __init__(self, name):
self.name = name
def print(self):
print("I am " + self.name)
a = ['rect','line','triangle']
#create object with name
for name in a:
code = '%s = Test("%s")' % (name, name)
exec(compile(code, '', 'exec'))
#call each print method
for name in a:
code = '%s.print()' % name
exec(compile(code, '', 'exec'))