【发布时间】:2012-12-15 05:04:58
【问题描述】:
假设我有这样的课程
class MyClass(AnotherClass):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def f(self):
#dostuff
我有字符串“我的班级”
str = "my class"
我可以这样做:
class_name_from_str = str.title().replace(" ", "") # now class_name_from_str is "MyClass"
如何使 class_name_from_str 可调用?我想要这样的东西:
callable_obj = some_process(class_name_from_str)
o = callable_obj(arg1, arg2)
o.f()
顺便说一下,我使用的是 Python 2.7
更新:正如Matti Virkkunen 在评论中建议的那样,一个好的解决方案是创建一个字典来映射字符串和类
my_calls_dict = {'my class' : MyClass, 'my other class' : MyOtherClass}
【问题讨论】:
标签: python-2.7 callable