在python中,假设我有一个字符串,其中包含我知道特定对象将具有的类函数的名称,我该如何调用它?
那是:
obj = MyClass() # this class has a method doStuff()
func = "doStuff"
# how to call obj.doStuff() using the func variable?
答案 0 :(得分:57)
使用“getattr”:http://docs.python.org/library/functions.html?highlight=getattr#getattr
obj = MyClass()
try:
func = getattr(obj, "dostuff")
func()
except AttributeError:
print "dostuff not found"