如何动态调用(a)模块内的函数?
例如:
class Class1(object):
pass
class Class2(object):
pass
# here I want to either instantiate object dynamically or dynamically pass
# a Class1 or Class2 object to some other method/class inside this module code
如何动态调用(a)模块内的函数?
例如:
class Class1(object):
pass
class Class2(object):
pass
# here I want to either instantiate object dynamically or dynamically pass
# a Class1 or Class2 object to some other method/class inside this module code
你的意思是这样的?
>>> class Class1(object):
... pass
...
>>> class Class2(object):
... pass
...
>>> def foo(cls):
... print cls
...
>>> import random
>>> classes = {'Class1': Class1, 'Class2': Class2}
>>> dynamic_class = classes['Class%d' % random.randint(1, 2)]
>>> foo(dynamic_class())
<__main__.Class1 object at 0x10b44ab50>
我假设您的意思是您想按名称访问这些类。
如果您想要的类在同一个模块中,请尝试globals()[classname]()
实例化该类。如果它在另一个模块中,请尝试vars(module)[classname]()
或getattr(module, classname)()
。
(classname
是一个包含类名的字符串;module
是对模块的引用,而不是字符串。)