简体   繁体   中英

Pass in function with default parameters

I have a function in Python f(a, b) and I am trying to define a new function g that takes in f with one argument already set, something like g(f(a = 5)) . This would be a simple example:

def sum(a, b):
   return a+b

def g(x, f):
   return f(x)

And I want to be able to evaluate g(5, sum(b=0)) . How do I do that?

Using functools.partial :

g(5, partial(sum, b=5))

Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords . If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords

The partial() is used for partial function application which “freezes” some portion of a function's arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:

basetwo = partial(int, base=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM