functools.partial wants to use a positional argument as a keyword argument

后端 未结 3 1584
情话喂你
情话喂你 2020-11-30 07:28

So I am trying to understand partial:

import functools

def f(x,y) :
    print x+y

g0 = functools.partial( f, 3 )
g0(1)

4 # Works as expected
         


        
3条回答
  •  情话喂你
    2020-11-30 08:03

    To expand on @Martijn-Pieters answer, this is how you can preserve the positional nature of the second parameter. Here, the argument to g2 is passed positionally as y:

    def f(x,y) :
        print x+y
    
    g2 = functools.partial( f, *[3] )
    g2(1)
    

    That works when we're trying to replace an initial set of the arguments of f. I don't know how to use partial to replace e.g. just the second argument of a 3-parameter function, and allow the first and third to be passed positionally. But you could do that with a lambda expression.

提交回复
热议问题