functools 模块中 提供了一个 partial 的函数,该函数允许固定一个或多个参数,从而创建一个新的偏函数,这个新的函数可以像原函数一样被调用,但是它会使用预先固定的参数值,这在需要重复使用某个函数但只改变部分参数时非常有用。
基本使用
案例一
from functools import partial
def add(a, b):
return a + b
# 创建一个偏函数,其中a=5
add_five = partial(add, 5)
# 使用偏函数
result = add_five(3) # 结果为8
print(result)
案例二
# 带有关键字参数的偏函数
def greet(greeting, name):
return f"{greeting}, {name}!"
say_hello = partial(greet, greeting="Hello")
message = say_hello(name="World") # 结果为 "Hello, World!"
print(message)
案例三
# 与类结合使用
class Person:
def __init__(self, name):
self.name = name
def introduce(self, prefix):
return f"{prefix}, my name is {self.name}."
# 创建一个偏函数,用于构造Person对象并立即调用introduce方法
make_person_introduction = partial(Person, name="Alice").introduce
introduction = make_person_introduction(prefix="Hi there")
print(introduction) # 输出: Hi there, my name is Alice.
1558

被折叠的 条评论
为什么被折叠?



