Python 偏函数 partial
partial 固定函数的部分参数,生成新的简化函数。
基本用法
Python
from functools import partial
# 固定第一个参数
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(4)) # 16
print(cube(3)) # 27
固定多个参数
Python
def greet(greeting, name, punctuation='!'):
return f"{greeting}, {name}{punctuation}"
# 固定 greeting
say_hello = partial(greet, 'Hello')
print(say_hello('Alice')) # Hello, Alice!
print(say_hello('Bob', '?')) # Hello, Bob?
# 固定多个参数
hi_alice = partial(greet, 'Hi', 'Alice')
print(hi_alice()) # Hi, Alice!
print(hi_alice(punctuation='.')) # Hi, Alice.
与内置函数配合
Python
from functools import partial
# 固定 int 的 base 参数
binary_to_int = partial(int, base=2)
hex_to_int = partial(int, base=16)
print(binary_to_int('1010')) # 10
print(hex_to_int('FF')) # 255
# 固定 print 的 sep 参数
space_print = partial(print, sep=' ')
space_print('a', 'b', 'c') # a b c
简化回调函数
Python
from functools import partial
def process_data(data, transform, validate=True):
if validate:
data = validate_data(data)
return transform(data)
# 创建预处理函数
uppercase_processor = partial(process_data, transform=str.upper)
lowercase_processor = partial(process_data, transform=str.lower)
data = "Hello World"
print(uppercase_processor(data)) # HELLO WORLD
print(lowercase_processor(data)) # hello world
作为函数参数
Python
from functools import partial
def apply_operation(numbers, operation):
return [operation(n) for n in numbers]
def multiply(x, y):
return x * y
numbers = [1, 2, 3, 4, 5]
# 固定乘数
double = partial(multiply, 2)
triple = partial(multiply, 3)
print(apply_operation(numbers, double)) # [2, 4, 6, 8, 10]
print(apply_operation(numbers, triple)) # [3, 6, 9, 12, 15]
partial 属性
Python
from functools import partial
def func(a, b, c):
return a + b + c
p = partial(func, 1, b=2)
print(p.func) # 原函数 <function func at ...>
print(p.args) # 固定位置参数 (1,)
print(p.keywords) # 固定关键字参数 {'b': 2}
partialmethod
用于绑定类方法的偏函数。
Python
from functools import partialmethod
class Cell:
def __init__(self):
self._alive = False
def set_state(self, state):
self._alive = bool(state)
set_alive = partialmethod(set_state, True)
set_dead = partialmethod(set_state, False)
cell = Cell()
cell.set_alive()
print(cell._alive) # True
cell.set_dead()
print(cell._alive) # False
partial vs lambda
Python
# partial 方式
from functools import partial
double = partial(lambda x, y: x * y, 2)
# lambda 方式
double_lambda = lambda x: x * 2
# partial 保留原函数信息
print(double.func) # 存在
print(double_lambda) # 只是匿名函数
要点总结
- partial 固定部分参数,创建简化函数
partial(func, *args, **keywords)语法- 可固定位置参数和关键字参数
- 适用于重复调用相同参数的场景
partialmethod用于类方法绑定- partial 保留原函数信息,便于调试
📝 发现内容有误?点击此处直接编辑