如何将参数与函数对象关联起来?
我是 python 新手,我发现“即使函数也是对象”这件事真的很酷,所以我只是在 PyShell 中使用函数。以下代码运行良好。
def add_num(a,b):
c = a + b
return c
x = add_num
x(5,2)
我想知道当我们分配 x = add_num 时是否可以存储参数。这样,每当我们调用 x() 时,它都会将 a 和 b(此处为 5 和 2)相加并返回结果。 x = add_num(5,2) 不起作用,因为 add_num(5,2) 实际上调用该函数并返回 7。
I am new to python and I find the "even functions are objects" thing really cool, so I was just playing with functions in the PyShell. The following code worked fine.
def add_num(a,b):
c = a + b
return c
x = add_num
x(5,2)
I was wondering whether we can store the parameters when we are assigning x = add_num. So that whenever we call x() it adds a and b (here 5 and 2) and returns the result. x = add_num(5,2) won't work since add_num(5,2) actually calls the function and returns 7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
functools
模块中的partial
函数 (文档)可以创建一个新的函数对象,其行为就像您想要的那样。您还可以仅指定一个参数,并在调用“partial”函数时提供另一个参数:
它也适用于关键字参数:
正如注释中所建议的,另一种选择是使用 lambda 表达式 ( 文档),这只是创建新函数的简写。
也可以像问题中所示那样修改原始函数,但在大多数情况下,这会被认为是不好的风格。如果您确实愿意,可以通过将参数添加为函数对象的
.func_defaults
属性(在旧版本的 Python 中称为.__defaults__
;文档)。The
partial
function in thefunctools
module (documentation) can create a new function object behaving like you want.You can also specify only one argument, and provide the other one when calling the "partial" function:
It works for keyword arguments too:
As suggested in the comments, another option is to use a
lambda
expression (documentation), which is just a shorthand for creating a new function.It is also possible to modify the original function like you show in the question, but in most cases this would be considered bad style. If you really want to, you can do so by adding the parameters as the
.func_defaults
attribute of the function object (called.__defaults__
in older versions of Python; documentation).印刷:
prints: