WHCSRL 技术网

python动态调用函数

1、类函数

  1. class TestA:
  2. def active_call_function(self,name):
  3. print("here is active_call_function.")
  4. # getaattr(module_name, function_name),module_name传self即可
  5. be_called_function = getattr(self, name)
  6. # 就直接调用。如果有其他参数,一样地传就好了
  7. be_called_function()
  8. pass
  9. def function_123(self):
  10. print("here is be_called_function.")
  11. if __name__ == '__main__':
  12. obj = TestA()
  13. obj.active_call_function("function_123")

带参数

  1. class TestA:
  2. def active_call_function(self,name,sss):
  3. print("here is active_call_function.")
  4. # getaattr(module_name, function_name),module_name传self即可
  5. be_called_function = getattr(self, name)
  6. # 就直接调用。如果有其他参数,一样地传就好了
  7. be_called_function(sss)
  8. pass
  9. def be_called_function_123(self,str11):
  10. print("here is be_called_function.","-----",str11)
  11. if __name__ == '__main__':
  12. obj = TestA()
  13. obj.active_call_function("be_called_function_123","test123")

2、普通函数

  1. def cl_pr(str2):
  2. print(str2)
  3. if __name__ == '__main__':
  4. eval("cl_pr")("test")

参考:https://www.jb51.net/article/214275.htm

推荐阅读