有時候我們想要通過字串
來直接呼叫函式,方便通過輸入的引數來直接控制呼叫的函式
常規操作
通過def
function1()
("function1"
)def
function2()
("function2"
)def
function3()
("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 =
(type
(a),
type
(eval
(a))
)b =
"[1,2,3]"
(type
(b),
type
(eval
(b))
)c =
"(4,5,6)"
(type
(c),
type
(eval
(c))
)
除此之外,它還能直接通過函式名的字串來呼叫函式a =
"10*20"
(eval
(a))
b ="pow(3,3)"
(eval
(b))
locals函式和globals函式def
function1()
("function1"
)def
function2()
("function2"
)def
function3()
("function3"
)def
call_fun_by_str
(fun_str)
:eval
(fun_str)()
call_fun_by_str(
"function2"
)
locals
和globals
函式提供了基於字典的訪問區域性和全域性變數的方式
通過locals和globals呼叫函式a =
1def
demo()
: x =
2#修改區域性變數
locals()
["x"]=
200print
(x)#2
#修改全域性變數
globals()
["a"]=
100print
(a)#100
demo(
)
getattr函式def
function1()
("function1"
)def
function2()
("function2"
)locals()
["function1"](
)globals()
["function2"](
)
getattr
函式可以用來獲取物件的屬性值
引數介紹
:
operator 的methodcallerclass
demo
(object):
a =100def
fun1
(self)
("fun1"
)def
fun2
(self)
("fun2"
)def
fun3
(self)
:#在類中呼叫另乙個函式
getattr
(self,
"fun2")(
)demo = demo(
)#呼叫類中的函式
getattr
(demo,
"fun1")(
)#fun1
getattr
(demo,
"fun3")(
)#fun2
#獲取類中的屬性值
(getattr
(demo,
"a")
)#100
#呼叫乙個不存在的屬性
(getattr
(demo,
"b")
)#對於不存在的屬性給乙個預設值,避免丟擲異常
(getattr
(demo,
"b",10)
)#10
methodcaller
函式對getattr
函式進行了封裝,底層的call
函式就呼叫getattr
函式
class
demo
(object):
a =100def
fun1
(self)
("fun1"
)def
fun2
(self)
("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...