我有这个班级
class Test(object):
def __init__(self, *args, **kwargs)
pass
def make(self):
pass
现在我有类名和函数名作为变量,如
class_name = "Test"
func_name = "make"
我想致电Test(**kwargs).make()
我试过这个
cls_name = "Test"
callback = getattr(cls_name, "make")
obj = callback()
答案 0 :(得分:2)
假设您的课程处于全球级别,您可以通过globals()
访问该课程。 (其他可能的选项是locals()
或vars()
。)例如:
>>> class Test(object):
... def __init__(self, *args, **kwargs):
... print("in test init")
... def make(self):
... print("in test make")
...
>>> cls_name = "Test"
>>> method_name = "make"
>>> callback = getattr(globals()[cls_name](), method_name)
in test init
>>> callback()
in test make
如果您的Test
课程位于其他模块中,则可以使用getattr(module_containing_test, cls_name)
代替globals()
查找。
答案 1 :(得分:0)
下面的代码似乎有效,我不知道它是否安全,因为大多数开发人员讨厌eval
。
class Test(object):
def __init__(self, *args, **kwargs):
print "I'm init"
def make(self):
print "I'm make"
class_name = "Test"
func_name = "make"
a = eval(class_name+"()")
eval('a'+"."+func_name+"()")
答案 2 :(得分:0)
# You have to prepend module name to class name
class_name = "moduletest.Test"
func_name = "make"
def get_class( kls ):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__( module )
for comp in parts[1:]:
m = getattr(m, comp)
return m
# You're creating object here, so have to pass all needed argument then
test = get_class(class_name)()
callback = getattr(test, func_name)
obj = callback()
答案 3 :(得分:0)