參考:
http://blog.sina.com.cn/s/blog_76e94d210100w1bl.html
https://taizilongxu.gitbooks.io/stackoverflow-about-python/content/59/README.html
有時候我想通過一個變量的字符串來調用這個函數。
例如:
class Test:
def foo(self):
print 'test'
直接調用這個類:
t = Test()
t.foo()
這時,我有個變量a
a = 'foo'
如何通過變量a的值’foo’調用foo呢,有如下方式:
1.用getattr函數
getattr(Test(),a)()
2.exec函數
exec("Test().%s()"%a)
收藏: