python 使用函数名的字符串调用函数 5种方法
废话不多说,直接上代码
# python 使用函数名的字符串调用函数 5种方法
def chinese(text):
print("chinese",text)
def english(text):
print("english",text)
func = 'chinese'
eval(func)("你好eval is evil")
locals()[func]("你好 locals")
globals()[func]("你好 globals")
class Foo:
def chinese(self,text):
print("chinese", text)
def english(self,text):
print("english", text)
foo = Foo()
func = getattr(foo, 'chinese')("你好 FOO")
from operator import methodcaller
methodcaller('chinese',"你好 methodcaller")(foo)