gpt4 book ai didi

python - 使用默认参数传入函数

转载 作者:太空宇宙 更新时间:2023-11-03 13:42:22 26 4
gpt4 key购买 nike

我在 Python f(a, b) 中有一个函数,我正在尝试定义一个接受 f 的新函数 g已经设置了一个参数,类似于 g(f(a = 5))。这将是一个简单的例子:

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

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

我希望能够计算 g(5, sum(b=0))。我该怎么做?

最佳答案

使用 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)

关于python - 使用默认参数传入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28359445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com