三种可以利用字符串调用同名函数的方法:
1. eval可以直接转换成函数调用;
2. locals、globals可以通过字典的方式访问局部、全局变量;
1 def funcA(): 2 print("A") 3 4 5 def funcB(): 6 print("B") 7 8 9 listfunc = ["funcA", "funcB"] 10 for item in listfunc: 11 # eval(item)() 12 # locals()[item]() 13 globals()[item]()
3. getattr(object,name) 就相当于 object.name,但是这里 name 可以为字符串变量。
1 class Func: 2 def funcA(self): 3 print("A") 4 5 6 def funcB(self): 7 print("B") 8 9 10 listfunc = ["funcA", "funcB"] 11 test = Func() 12 for item in listfunc: 13 getattr(test, item)()
object可以是模块
浙公网安备 33010602011771号