python通過字串來呼叫函式

2021-10-10 15:18:43 字數 3674 閱讀 3699

有時候我們想要通過字串來直接呼叫函式,方便通過輸入的引數來直接控制呼叫的函式

常規操作

def

function1()

:print

("function1"

)def

function2()

:print

("function2"

)def

function3()

:print

("function3"

)def

call_fun_by_str

(fun_str)

:if fun_str ==

"function1"

: function1(

)elif fun_str ==

"function2"

: function2(

)elif fun_str ==

"function3"

: function3(

)call_fun_by_str(

"function2"

)

通過判斷字串是否等於函式名,然後再來決定呼叫的函式。看起來感覺有那麼一點點的多餘,python作為追求簡潔的語言,還提供了另外幾種不同的方式通過字串呼叫函式的方法。

eval函式

python內建的eval函式可以將符合字典列表元祖格式的字串轉換成字典列表元祖

a =

""print

(type

(a),

type

(eval

(a))

)b =

"[1,2,3]"

print

(type

(b),

type

(eval

(b))

)c =

"(4,5,6)"

print

(type

(c),

type

(eval

(c))

)

還能對字串格式的表示式進行計算

a =

"10*20"

print

(eval

(a))

b ="pow(3,3)"

print

(eval

(b))

除此之外,它還能直接通過函式名的字串來呼叫函式

def

function1()

:print

("function1"

)def

function2()

:print

("function2"

)def

function3()

:print

("function3"

)def

call_fun_by_str

(fun_str)

:eval

(fun_str)()

call_fun_by_str(

"function2"

)

locals函式和globals函式

localsglobals函式提供了基於字典的訪問區域性和全域性變數的方式

a =

1def

demo()

: x =

2#修改區域性變數

locals()

["x"]=

200print

(x)#2

#修改全域性變數

globals()

["a"]=

100print

(a)#100

demo(

)

通過locals和globals呼叫函式

def

function1()

:print

("function1"

)def

function2()

:print

("function2"

)locals()

["function1"](

)globals()

["function2"](

)

getattr函式

getattr函式可以用來獲取物件的屬性值

引數介紹

class

demo

(object):

a =100def

fun1

(self)

:print

("fun1"

)def

fun2

(self)

:print

("fun2"

)def

fun3

(self)

:#在類中呼叫另乙個函式

getattr

(self,

"fun2")(

)demo = demo(

)#呼叫類中的函式

getattr

(demo,

"fun1")(

)#fun1

getattr

(demo,

"fun3")(

)#fun2

#獲取類中的屬性值

print

(getattr

(demo,

"a")

)#100

#呼叫乙個不存在的屬性

print

(getattr

(demo,

"b")

)#對於不存在的屬性給乙個預設值,避免丟擲異常

print

(getattr

(demo,

"b",10)

)#10

operator 的methodcaller

methodcaller函式對getattr函式進行了封裝,底層的call函式就呼叫getattr函式

class

demo

(object):

a =100def

fun1

(self)

:print

("fun1"

)def

fun2

(self)

:print

("fun2"

)def

fun3

(self)

:#在類中呼叫另乙個函式

getattr

(self,

"fun2")(

)from operator import methodcaller

demo = demo(

)methodcaller(

"fun1"

)(demo)

通過同名字串來呼叫函式

相信使用python的各位童鞋,總會有這樣的需求 通過乙個同名的字串來呼叫乙個函式。其他的語言是如何實現,不太清楚。但是python提供乙個強大的內建函式getattr 可以實現這樣的功能。getattr 的函式原型為 getattr object,str name 其返回物件object中名字為s...

Python 反射,通過字串來匯入模組

反射 通過字串額形式,匯入模組 通過字串的形式,去模組中尋找指定函式,並執行函式。import 字串形式的模組名稱 就可以匯入相應的模組 通過內建函式 getattr 模組名,函式的字串名稱 來指定需要執行的函式 注意找到了函式,還需要在函式名後面加 來執行函式。getattr,setattr,ha...

Python的partition字串函式

rpartition s.rpartition sep head,sep,tail search for the separator sep in s,starting at the end of s,and return the part before it,the separator itsel...