Differences between functools.partial and a similar lambda?

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)

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

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

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)?


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

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

    g1(x, y, z)
    

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

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

    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.)

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


  • I believe that the class method thing only applies to functions assigned during class definition. Functions assigned later are not treated specially.

    Other than that, I'd personally favor lambdas since they're more common and hence make the code easier to understand.

    class Foo(object):
        def __init__(self, base):
            self.int = lambda x:int(x, base)
    
    print Foo(4).int('11')
    

    Yes, lambda will "suffer" from this. partial doesn't have this problem because it is an object with the call operator overloaded, rather than a real function.

    But using a lambda like this in a class definition is just misuse.

    链接地址: http://www.djcxy.com/p/51288.html

    上一篇: Tkinter按钮命令在运行程序时激活?

    下一篇: functools.partial和类似的lambda之间的区别?