functools.partial和类似的lambda之间的区别? [英] Differences between functools.partial and a similar lambda?

查看:256
本文介绍了functools.partial和类似的lambda之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,假设我有一个函数f,我想将它与一些辅助参数一起传递(为简单起见,它只是第一个保留变量的参数).

In Python, suppose I have a function f that I want to pass around with some secondary arguments (assume for simplicity that it's just the first argument that remains variable).

这两种方式(如果有)之间有什么区别?

What are the differences between doing it these two ways (if any)?

# Assume secondary_args and secondary_kwargs have been defined

import functools

g1 = functools.partial(f, *secondary_args, **secondary_kwargs)
g2 = lambda x: f(x, *secondary_args, **secondary_kwargs)

例如,在partial文档页面中,有以下引用:

In the doc page for partial, for example, there is this quote:

在类中定义的

partial对象的行为类似于静态方法,并且在实例属性查找期间不会转换为绑定方法.

partial objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.

如果将lambda方法用于从提供给类的参数(通过构造函数或稍后通过函数)中创建类方法,该方法会遭受此苦难吗?

Will the lambda-method suffer from this if used to make a class method from arguments supplied to the class (either in the constructor or through a function later on)?

推荐答案

  1. lambda函数具有与标准函数相同的类型,因此其行为类似于实例方法.

  1. A lambda function has the same type as a standard function, so it will behave like an instance method.

示例中的partial对象可以这样调用:

The partial object in your example can be called like this:

g1(x, y, z)

导致此调用(无效的Python语法,但您知道了):

leading to this call (not valid Python syntax, but you get the idea):

f(*secondary_args, x, y, z, **secondary_kwargs)

lambda仅接受单个参数,并使用不同的参数顺序. (当然,这两个差异都可以克服–我只是在回答您给出的两个版本之间的差异.)

The lambda only accepts a single argument and uses a different argument order. (Of course both of these differences can be overcome – I'm just answering what the differences between the two versions you gave are.)

partial对象的执行比等效的lambda的执行略快.

Execution of the partial object is slightly faster than execution of the equivalent lambda.

这篇关于functools.partial和类似的lambda之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆