简体   繁体   English

使用默认参数传入函数

[英]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)) . 我在Python f(a, b)有一个函数,我试图定义一个新函数g ,它接受f已经设置了一个参数,类似于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)) . 我希望能够评估g(5, sum(b=0)) How do I do that? 我怎么做?

Using functools.partial : 使用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 . 返回一个新的部分对象,当被调用时,其行为类似于使用位置参数args和关键字参数关键字调用的func。 If more arguments are supplied to the call, they are appended to args. 如果为调用提供了更多参数,则将它们附加到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. partial()用于部分函数应用程序,它“冻结”函数的参数和/或关键字的某些部分,从而产生具有简化签名的新对象。 For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two: 例如,partial()可用于创建一个callable,其行为类似于int()函数,其中base参数默认为2:

basetwo = partial(int, base=2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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