日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

Python函數調用的九大方法,鮮為人知

來源: 責編: 時間:2023-12-21 17:10:15 205觀看
導讀分享調用函數的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。其中一些函數調用方法,在函數式編程或元編程場景中大量使用。相信你在今后的學習或工作中會遇到!1.

分享調用函數的9種方法:getattr, partial, eval, __dict__, globals, exec, attrgetter, methodcaller, 和 __call__。其中一些函數調用方法,在函數式編程或元編程場景中大量使用。相信你在今后的學習或工作中會遇到!rL328資訊網——每日最新資訊28at.com

rL328資訊網——每日最新資訊28at.com

1. 直接調用函數(__call__)

最簡單最直接的使用方法:rL328資訊網——每日最新資訊28at.com

def func():    print('Hello, world!')func() # Hello, world!func.__call__() # 一樣的

2. partial 函數

在python的內置庫functools中有一個partial函數,可以讓我們可以把一個函數的一部分參數填入,然后調用。看起來沒什么用,遇到的時候有大用。rL328資訊網——每日最新資訊28at.com

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!

3. eval 函數

如果需要動態執行函數,可以使用 eval 來執行動態代碼。rL328資訊網——每日最新資訊28at.com

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

4. getattr 函數

運行類中的靜態方法rL328資訊網——每日最新資訊28at.com

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()

5. dict 方法

首先我們需要知道,每個python對象都有一個內置的__dict__()方法,這個方法返回一個字典,包含了對象的所有屬性。如下圖,我們可以看到list的__dict__()方法返回的所有屬性,其中紅框內的,你是否有些熟悉?rL328資訊網——每日最新資訊28at.com

rL328資訊網——每日最新資訊28at.com

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() # 為什么不這樣用?

6. globals 函數

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

7. exec 函數

你可以在一個字符串中定義你的函數,并使用compile函數將它編譯成字節碼,然后使用exec來執行它。rL328資訊網——每日最新資訊28at.com

# 方式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'))

8. attrgetter 函數

在內置庫operator中,有一個獲取屬性的方法,叫做attrgetter,我們可以通過它獲取函數后執行。rL328資訊網——每日最新資訊28at.com

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

9. methodcaller 函數

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__。rL328資訊網——每日最新資訊28at.com

請仔細品味,思考下他們的使用場景。其中一些函數調用方法,在函數式編程或元編程場景中大量使用。相信你在今后的學習或工作中會遇到!rL328資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-51222-0.htmlPython函數調用的九大方法,鮮為人知

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 13個你不知道的Python技巧

下一篇: AIGC在趣丸科技廣告素材場景下賦能業務的探索實踐

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 岗巴县| 防城港市| 凯里市| 桃园县| 昌平区| 油尖旺区| 金平| 莱阳市| 阳原县| 山阳县| 凤阳县| 正定县| 思茅市| 长乐市| 高尔夫| 古田县| 确山县| 马尔康县| 社会| 河南省| 炉霍县| 临城县| 怀宁县| 太谷县| 林口县| 莱芜市| 晴隆县| 东乌| 遵义市| 赤壁市| 永登县| 台江县| 岱山县| 福清市| 乌拉特后旗| 柳林县| 海安县| 康定县| 鄱阳县| 通许县| 莎车县|