PYTHON函數(shù)工具partial用法小結(jié)
functools.partial 是 Python 的一個(gè)高階函數(shù)工具,用于固定函數(shù)的某些參數(shù),生成新的函數(shù)對(duì)象。它的核心作用是參數(shù)預(yù)填充,減少重復(fù)代碼。這在函數(shù)式編程中是一個(gè)常見(jiàn)的技術(shù)。python中partial被稱為偏函數(shù)。
基本語(yǔ)法
from functools import partial new_func = partial(func, *args, **kwargs) - func:要部分應(yīng)用的原始函數(shù) -*args:要固定的位置參數(shù) - **kwargs:要固定的關(guān)鍵字參數(shù) - 返回一個(gè)新的可調(diào)用對(duì)象 new_func
以下是詳細(xì)用法和示例:
一、基礎(chǔ)概念
from functools import partial
#原函數(shù)
def func(a, b, c=3):
return a + b + c
#固定參數(shù)生成新函數(shù)
new_func = partial(func, 1, c=10) # 固定 a=1, c=10
#調(diào)用時(shí)只需傳遞剩余參數(shù)
print(new_func(2)) # 輸出: 1 + 2 + 10 = 13
作用:通過(guò)預(yù)填充部分參數(shù),生成一個(gè)更簡(jiǎn)潔的調(diào)用接口。
二、核心用法
固定位置參數(shù)
from functools import partial
def power(base, exponent):
return base ** exponent
#固定 exponent=2,生成平方函數(shù)See:這有點(diǎn)像函數(shù)工廠
square = partial(power, exponent=2)
print(square(3)) # 3^2=9
#固定 pxponent=3,生成立方函數(shù)
cube = partial(power, exponent=3)
print(cube(2)) # 2^3=8
固定關(guān)鍵字參數(shù)
def greet(greeting, name="Guest"):
return f"{greeting}, {name}!"
#固定 greeting="Hello"
say_hello = partial(greet, greeting="Hello")
print(say_hello("Alice")) # "Hello, Alice!"
混合參數(shù)綁定
def connect(host, port=8080, timeout=10):
print(f"Connecting to {host}:{port} (timeout={timeout}s)")
#固定 host 和 timeout,生成新函數(shù)
fast_connect = partial(connect, "example.com", timeout=5)
fast_connect(9090) # 輸出: Connecting to example.com:9090 (timeout=5s)
三、典型應(yīng)用場(chǎng)景
GUI 編程參數(shù)綁定
import tkinter as tk
from functools import partial
def create_button(root, text, command):
btn = tk.Button(root, text=text, command=command)
btn.pack()
root = tk.Tk()
#為不同按鈕綁定不同參數(shù)
create_button(root, "Btn1", partial(print, "Button 1 clicked"))
create_button(root, "Btn2", partial(print, "Button 2 clicked"))

數(shù)據(jù)處理管道
from functools import partial data = [1, 2, 3, 4, 5] #固定冪次生成函數(shù) square = partial(map, lambda x: x**2) cube = partial(map, lambda x: x**3) print(list(square(data))) # [1, 4, 9, 16, 25] print(list(cube(data))) # [1, 8, 27, 64, 125]
裝飾器參數(shù)預(yù)配置
from functools import partial, wraps
def log(level, message):
print(f"[{level}] {message}")
info = partial(log, "INFO")
#定義裝飾器工廠
def decorator(level): # 關(guān)鍵:定義裝飾器工廠
def actual_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Decorated with {level.args[0]}")
return func(*args, **kwargs)
return wrapper
return actual_decorator
#正確應(yīng)用裝飾器
@decorator(level=info)
def my_function():
pass
my_function() # 輸出: Decorated with INFO
四、進(jìn)階技巧
獲取原函數(shù)信息
from functools import partial
def example(a, b):
pass
p = partial(example, 1)
print(p.func) # <function example at ...>
print(p.args) # (1,)
print(p.keywords) # {}
支持 name 屬性(Python 3.3+)
from functools import partial
def my_func():
pass
p = partial(my_func)
print(p.__name__) # 輸出: my_func
可哈希性
from functools import partial
#需要實(shí)現(xiàn) hash 方法才能作為字典鍵
class HashablePartial(partial):
def __hash__(self):
return hash((self.func, self.args, frozenset(self.keywords.items())))
hp = HashablePartial(print, "test")
cache = {hp: "cached value"}
五、注意事項(xiàng)
1.參數(shù)順序敏感
固定參數(shù)必須按原函數(shù)參數(shù)順序傳遞:
from functools import partial
def func(a, b, c):
return (a+b)*c
#正確: 固定 a=1, b=2
p = partial(func, 1, 2)
print(p(3)) # 9
#錯(cuò)誤: 無(wú)法直接固定 c=3
p = partial(func,3) #3 傳遞給了a
print(p(1,2)) #8 即:(3+1)*2
2.不可直接修改
partial 對(duì)象不可變,若需修改需重新創(chuàng)建。
3.與 lambda 的區(qū)別
partial 性能優(yōu)于 lambda,但功能更受限于參數(shù)綁定。
到此這篇關(guān)于PYTHON函數(shù)工具partial用法小結(jié)的文章就介紹到這了,更多相關(guān)PYTHON partial內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python判斷遠(yuǎn)程服務(wù)器上Excel文件是否被人打開的方法
這篇文章主要介紹了Python如何判斷遠(yuǎn)程服務(wù)器上Excel文件是否被人打開,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
Python深入分析@property裝飾器的應(yīng)用
這篇文章主要介紹了Python @property裝飾器的用法,在Python中,可以通過(guò)@property裝飾器將一個(gè)方法轉(zhuǎn)換為屬性,從而實(shí)現(xiàn)用于計(jì)算的屬性,下面文章圍繞主題展開更多相關(guān)詳情,感興趣的小伙伴可以參考一下2022-07-07
Python+pytorch實(shí)現(xiàn)天氣識(shí)別
這篇文章主要為大家詳細(xì)介紹了如何利用Python+pytorch實(shí)現(xiàn)天氣識(shí)別功能,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下2022-10-10
tensorflow官方github預(yù)訓(xùn)練模型下載方式
這篇文章主要介紹了tensorflow官方github預(yù)訓(xùn)練模型下載方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
Python實(shí)現(xiàn)的排列組合計(jì)算操作示例
這篇文章主要介紹了Python實(shí)現(xiàn)的排列組合計(jì)算操作,涉及Python數(shù)學(xué)運(yùn)算的相關(guān)函數(shù)與使用技巧,需要的朋友可以參考下2017-10-10
Python實(shí)現(xiàn)將Excel某范圍單元格內(nèi)容截圖
Openpyxl是一個(gè)強(qiáng)大的Python庫(kù),主要用于讀取、寫入和操作Excel文件,本文將使用Openpyxl實(shí)現(xiàn)將Excel某范圍單元格內(nèi)容截圖,感興趣的可以了解下2024-11-11
pytorch中forwod函數(shù)在父類中的調(diào)用方式解讀
這篇文章主要介紹了pytorch中forwod函數(shù)在父類中的調(diào)用方式解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02

