PYTHON函数工具partial用法小结!

PYTHON函数工具partial用法小结!

作者:看烟波浩渺
functools.partial 是 Python 的一个高阶函数工具,用于固定函数的某些参数,生成新的函数对象,具有一定的参考价值,感兴趣的可以了解一下。

基本语法

1
2
3
4
5
6
7
8
9
from functools import partial
new_func = partial(func, *args, **kwargs)
- func:要部分应用的原始函数
-*args:要固定的位置参数
- **kwargs:要固定的关键字参数
- 返回一个新的可调用对象 new_func

以下是详细用法和示例:

一、基础概念

1
2
3
4
5
6
7
8
9
10
11
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

作用:通过预填充部分参数,生成一个更简洁的调用接口。

二、核心用法

固定位置参数

1
2
3
4
5
6
7
8
9
10
11
12
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

固定关键字参数

1
2
3
4
5
6
def greet(greeting, name="Guest"):
return f"{greeting}, {name}!"
#固定 greeting="Hello"
say_hello = partial(greet, greeting="Hello")
print(say_hello("Alice"))  # "Hello, Alice!"

混合参数绑定

1
2
3
4
5
6
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 编程参数绑定

1
2
3
4
5
6
7
8
9
10
11
12
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"))

 

数据处理管道

1
2
3
4
5
6
7
8
9
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]

装饰器参数预配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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

四、进阶技巧

获取原函数信息

1
2
3
4
5
6
7
8
9
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+)

1
2
3
4
5
6
7
from functools import partial
def my_func():
    pass
p = partial(my_func)
print(p.__name__)  # 输出: my_func

可哈希性
from functools import partial

#需要实现 hash 方法才能作为字典键

1
2
3
4
5
6
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.参数顺序敏感

固定参数必须按原函数参数顺序传递:

1
2
3
4
5
6
7
8
9
10
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用法小结的文章就介绍到这了。

 

学习资料见知识星球。

以上就是今天要分享的技巧,你学会了吗?若有什么问题,欢迎在下方留言。

快来试试吧,小琥 my21ke007。获取 1000个免费 Excel模板福利​​​​!

更多技巧, www.excelbook.cn

欢迎 加入 零售创新 知识星球,知识星球主要以数据分析、报告分享、数据工具讨论为主;

Excelbook.cn Excel技巧 SQL技巧 Python 学习!

你将获得:

1、价值上万元的专业的PPT报告模板。

2、专业案例分析和解读笔记。

3、实用的Excel、Word、PPT技巧。

4、VIP讨论群,共享资源。

5、优惠的会员商品。

6、一次付费只需129元,即可下载本站文章涉及的文件和软件。

文章版权声明 1、本网站名称:Excelbook
2、本站永久网址:http://www.excelbook.cn
3、本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长王小琥进行删除处理。
4、本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责。
5、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报。
6、本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新。

THE END
分享
二维码
< <上一篇
下一篇>>