最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

PYTHON函數(shù)工具partial用法小結(jié)

 更新時間:2025年07月13日 10:28:35   作者:看煙波浩渺  
functools.partial 是 Python 的一個高階函數(shù)工具,用于固定函數(shù)的某些參數(shù),生成新的函數(shù)對象,具有一定的參考價值,感興趣的可以了解一下

functools.partial 是 Python 的一個高階函數(shù)工具,用于固定函數(shù)的某些參數(shù),生成新的函數(shù)對象。它的核心作用是參數(shù)預(yù)填充,減少重復(fù)代碼。這在函數(shù)式編程中是一個常見的技術(shù)。python中partial被稱為偏函數(shù)。

基本語法

from functools import partial

new_func = partial(func, *args, **kwargs)


- func:要部分應(yīng)用的原始函數(shù)
-*args:要固定的位置參數(shù)
- **kwargs:要固定的關(guān)鍵字參數(shù)
- 返回一個新的可調(diào)用對象 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ù)
print(new_func(2))  # 輸出: 1 + 2 + 10 = 13

作用:通過預(yù)填充部分參數(shù),生成一個更簡潔的調(diào)用接口。

二、核心用法

固定位置參數(shù)

from functools import partial

def power(base, exponent):
    return base ** exponent

#固定 exponent=2,生成平方函數(shù)See:這有點像函數(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)用場景

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

#需要實現(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"}

五、注意事項

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
#錯誤: 無法直接固定 c=3
p = partial(func,3) #3 傳遞給了a
print(p(1,2)) #8 即:(3+1)*2

2.不可直接修改
partial 對象不可變,若需修改需重新創(chuàng)建。

3.與 lambda 的區(qū)別
partial 性能優(yōu)于 lambda,但功能更受限于參數(shù)綁定。

到此這篇關(guān)于PYTHON函數(shù)工具partial用法小結(jié)的文章就介紹到這了,更多相關(guān)PYTHON partial內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

永兴县| 德州市| 山东| 罗城| 深水埗区| 家居| 都江堰市| 西昌市| 贞丰县| 花莲市| 余江县| 大名县| 临高县| 贵南县| 宁津县| 百色市| 南溪县| 仪陇县| 蚌埠市| 上林县| 兴隆县| 齐齐哈尔市| 水富县| 刚察县| 灵石县| 方山县| 尚志市| 扎赉特旗| 大化| 镇坪县| 富蕴县| 威海市| 郯城县| 祥云县| 阿拉善左旗| 长垣县| 临安市| 工布江达县| 香格里拉县| 海门市| 宜城市|