python把字符串轉換成函數或者方法


先看一個例子:

def foo():
    print("foo1")

def bar():
    print("bar2")

func_list = ["foo" ,"bar"]

for func in func_list:
    func()

>>>

Traceback (most recent call last):
File "D:/data/AutoTest_code/ML/test.py", line 21, in <module>
func()
TypeError: 'str' object is not callable

 
        

我們希望遍歷執行列表中的函數,但是從列表中獲得的函數名是字符串,所以會提示類型錯誤,字符串對象是不可以調用的。如果我們想要字符串變成可調用的對象呢?或是想通過變量調用模塊的屬性和類的屬性呢?以下有三種方法可以實現。

eval()

func_list = ["foo" ,"bar"]

for func in func_list:
  
locals()[func]()
>>> foo1 bar2

eval() 通常用來執行一個字符串表達式,並返回表達式的值。在這里它將字符串轉換成對應的函數。eval() 功能強大但是比較危險(eval is evil),不建議使用。

locals()

func_list = ["foo" ,"bar"]

for func in func_list:
  
locals()[func]()
 
         
>>>
foo1
bar2

globals()

func_list = ["foo" ,"bar"]

for func in func_list:
  
globals()[func]()
>>> 
foo1
bar2

locals() 和 globals() 是python的兩個內置函數,通過它們可以一字典的方式訪問局部和全局變量。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM