functools.partial 是 python 的一个高阶函数工具,用于固定函数的某些参数,生成新的函数对象。它的核心作用是参数预填充,减少重复代码。这在函数式编程中是一个常见的技术。python中partial被称为偏函数。
基本语法
from functools import partial new_func = partial(func, *args, **kwargs) - func:要部分应用的原始函数 -*args:要固定的位置参数 - **kwargs:要固定的关键字参数 - 返回一个新的可调用对象 new_func
以下是详细用法和示例:
一、基础概念
from functools import partial
#原函数
def func(a, b, c=3):
return a + b + c
#固定参数生成新函数
new_func = partial(func, 1, c=10) # 固定 a=1, c=10
#调用时只需传递剩余参数
print(new_func(2)) # 输出: 1 + 2 + 10 = 13
作用:通过预填充部分参数,生成一个更简洁的调用接口。
二、核心用法
固定位置参数
from functools import partial
def power(base, exponent):
return base ** exponent
#固定 exponent=2,生成平方函数see:这有点像函数工厂
square = partial(power, exponent=2)
print(square(3)) # 3^2=9
#固定 pxponent=3,生成立方函数
cube = partial(power, exponent=3)
print(cube(2)) # 2^3=8
固定关键字参数
def greet(greeting, name="guest"):
return f"{greeting}, {name}!"
#固定 greeting="hello"
say_hello = partial(greet, greeting="hello")
print(say_hello("alice")) # "hello, alice!"
混合参数绑定
def connect(host, port=8080, timeout=10):
print(f"connecting to {host}:{port} (timeout={timeout}s)")
#固定 host 和 timeout,生成新函数
fast_connect = partial(connect, "example.com", timeout=5)
fast_connect(9090) # 输出: connecting to example.com:9090 (timeout=5s)
三、典型应用场景
gui 编程参数绑定
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()
#为不同按钮绑定不同参数
create_button(root, "btn1", partial(print, "button 1 clicked"))
create_button(root, "btn2", partial(print, "button 2 clicked"))

数据处理管道
from functools import partial data = [1, 2, 3, 4, 5] #固定幂次生成函数 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]
装饰器参数预配置
from functools import partial, wraps
def log(level, message):
print(f"[{level}] {message}")
info = partial(log, "info")
#定义装饰器工厂
def decorator(level): # 关键:定义装饰器工厂
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
#正确应用装饰器
@decorator(level=info)
def my_function():
pass
my_function() # 输出: decorated with info
四、进阶技巧
获取原函数信息
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
#需要实现 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.参数顺序敏感
固定参数必须按原函数参数顺序传递:
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 对象不可变,若需修改需重新创建。
3.与 lambda 的区别
partial 性能优于 lambda,但功能更受限于参数绑定。
到此这篇关于python函数工具partial用法小结的文章就介绍到这了,更多相关python partial内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论