2018年3月8日 星期四

[ Python 常見問題 ] Calling a function of a module by using its name (a string)

Source From Here 
Question 
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo, and I have a string whose contents are "bar". What is the best way to go about calling foo.bar()? I need to get the return value of the function, which is why I don't just use eval. I figured out how to do it by using eval to define a temp function that returns the result of that function call, but I'm hoping that there is a more elegant way to do this. 

How-To 
Assuming module foo with method bar
  1. import foo  
  2. method_to_call = getattr(foo, 'bar')  
  3. result = method_to_call()  
As far as that goes, lines 2 and 3 can be compressed to: 
  1. result = getattr(foo, 'bar')()  
if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods, module-level methods, class methods... the list goes on.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...