分享調用函數的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。其中一些函數調用方法,在函數式編程或元編程場景中大量使用。相信你在今后的學習或工作中會遇到!
最簡單最直接的使用方法:
def func(): print('Hello, world!')func() # Hello, world!func.__call__() # 一樣的
在python的內置庫functools中有一個partial函數,可以讓我們可以把一個函數的一部分參數填入,然后調用。看起來沒什么用,遇到的時候有大用。
from functools import partial# 請仔細品!def func(domain, user): echo = f"Hello, {user}@{domain}!" print(echo)func_userA = partial(func, user="userA")func_userB = partial(func, user="userB")func_userA("example.com") # Hello, userA@example.com!func_userB("example.com") # Hello, userB@example.com!
如果需要動態執行函數,可以使用 eval 來執行動態代碼。
import sysdef pre_task(): print("running pre_task")def task(): print("running task")def post_task(): print("running post_task")cmdList = ["pre_task()","task()","post_task()"]for cmd in cmdList: eval(cmd) # 執行函數# running pre_task# running task# running post_task
運行類中的靜態方法
import sysclass Task: @staticmethod def pre_task(): print("running pre_task") @staticmethod def task(): print("running task") @staticmethod def post_task(): print("running post_task")#?? 沒有括號的字符串。cmdList = ["pre_task", "task", "post_task"]task = Task()for cmd in cmdList: func = getattr(task, cmd) func()
首先我們需要知道,每個python對象都有一個內置的__dict__()方法,這個方法返回一個字典,包含了對象的所有屬性。如下圖,我們可以看到list的__dict__()方法返回的所有屬性,其中紅框內的,你是否有些熟悉?
class Task: @staticmethod def pre_task(): print("running pre_task") @staticmethod def task(): print("running task") @staticmethod def post_task(): print("running post_task")func = Task.__dict__.get("pre_task")func.__func__() # running pre_taskfunc() # 為什么不這樣用?
import sysdef pre_task(): print("running pre_task")def task(): print("running task")def post_task(): print("running post_task")cmdList = ["pre_task", "task", "post_task"]for cmd in cmdList: func = globals().get(cmd) func()# running pre_task# running task# running post_task
你可以在一個字符串中定義你的函數,并使用compile函數將它編譯成字節碼,然后使用exec來執行它。
# 方式1pre_task = """print("running pre_task")"""exec(compile(pre_task, '', 'exec'))# running pre_task# 方式2with open('./source.txt') as f: source = f.read() exec(compile(source, 'source.txt', 'exec'))
在內置庫operator中,有一個獲取屬性的方法,叫做attrgetter,我們可以通過它獲取函數后執行。
from operator import attrgetterclass People: def speak(self, dest): print("Hello, %s" %dest)p = People()caller = attrgetter("speak")caller(p)("Tony") # Hello, Tony# 本文第四條caller2 = getattr(p, "speak")caller2("Tony") # Hello, Tony
from operator import methodcallerclass People: def speak(self, dest): print(f"Hello, {dest}")caller = methodcaller("speak", "Tony")p = People()caller(p)
總結下,本文分享了使用函數的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。
請仔細品味,思考下他們的使用場景。其中一些函數調用方法,在函數式編程或元編程場景中大量使用。相信你在今后的學習或工作中會遇到!
本文鏈接:http://www.www897cc.com/showinfo-26-51222-0.htmlPython函數調用的九大方法,鮮為人知
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 13個你不知道的Python技巧