在 Python 中将函数输入的默认值设置为等于另一个输入
考虑下面的函数,它在 Python 中不起作用,但我将用它来解释我需要做什么。
def exampleFunction(a, b, c = a):
...function body...
也就是说,我想为变量 c 分配与变量 a 相同的值,除非指定了替代值。上面的代码在Python中不起作用。有办法做到这一点吗?
Consider the following function, which does not work in Python, but I will use to explain what I need to do.
def exampleFunction(a, b, c = a):
...function body...
That is I want to assign to variable c
the same value that variable a
would take, unless an alternative value is specified. The above code does not work in python. Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
关键字参数的默认值不能是变量(如果是,则在定义函数时将其转换为固定值。)通常用于将参数传递给主函数:
If
None
可能是一个有效值,解决方案是使用*args
/**kwargs
魔法(如卡尔的答案),或使用 sentinel 对象 。执行此操作的库包括 attrs 和 棉花糖,以及在我看来,它更干净而且可能更快。唯一使
c ismissing
为true的方法是c
完全是您在此处创建的虚拟对象。The default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function:
If
None
could be a valid value, the solution is to either use*args
/**kwargs
magic as in carl's answer, or use a sentinel object. Libraries that do this include attrs and Marshmallow, and in my opinion it's much cleaner and likely faster.The only way for
c is missing
to be true is forc
to be exactly that dummy object you created there.这种通用模式可能是最好且最具可读性的:
您必须小心
None
不是c
的有效状态。如果你想支持“None”值,你可以这样做:
This general pattern is probably the best and most readable:
You have to be careful that
None
is not a valid state forc
.If you want to support 'None' values, you can do something like this:
一种方法是这样的:
One approach is something like: