1. 程式人生 > 其它 >python把字串轉換成函式或者方法

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的兩個內建函式,通過它們可以一字典的方式訪問區域性和全域性變數。

Airtest自動化測試交流群:739857090