python中用字符串来调用函数

参考: 
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)

收藏:

https://blog.csdn.net/u012375924/article/details/51779396

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章