python文字列タイプの関数名で関数を呼び出す
python文字列タイプの関数名で関数を呼び出す eval locals()およびglobals() getattr() operatorのmethodcaller関数
def func():
print("hello world")
if __name__ == '__main__':
str01 = "func"
str_2_func = eval(str01)
str_2_func() # hello world
print(type(str_2_func)) #
def func01():
print("hello world func01")
def func02():
print("hello world func02")
if __name__ == '__main__':
locals()['func01']() # hello world func01
globals()['func02']() # hello world func02
# python ,getattr(object,name) object.name
class A(object):
def to_eat(self):
print("eat")
def to_sleep(self):
print("sleep")
if __name__ == "__main__":
a = A()
# 1:object
# 2:name
func01 = getattr(a, "to_eat")
func01()
func02 = getattr(a, "to_sleep")
func02()
# operator methodcaller , AttributeError
from operator import methodcaller
class A(object):
def func(self):
print("func")
if __name__ == '__main__':
a = A()
# methodcaller( )( )
methodcaller("func")(a)