[英]How to use passed arguments as default parameter values in Python?
Given a function with multiple arguments, where all but the first one are variable.给定一个带有多个参数的函数,其中除了第一个参数之外的所有参数都是可变的。
Eg: def f(a, b = .., ...)
例如:
def f(a, b = .., ...)
I am looking for minimalist python-code that realizes the intuitive code below:我正在寻找实现以下直观代码的极简python代码:
def f(a, b = a, ...)
Hence, I could not find any satisfying answers I am asking here although I am without doubts that the answers to this question have been given already somewhere - in that case i apologize.因此,我在这里找不到任何令人满意的答案,尽管我毫不怀疑这个问题的答案已经在某处给出了 - 在这种情况下,我深表歉意。 Cheers!
干杯!
I specify by another example my desired functionality again intuitively by wrong code:我通过另一个示例再次通过错误的代码直观地指定了我想要的功能:
def f(a,b,c, d = 0, e = [], f = b, g = c, h = a):
...
Thank you in advance!先感谢您!
According to the Python docs :根据Python 文档:
the expression [used as default parameter value] is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call.
表达式 [用作默认参数值] 在定义函数时计算一次,并且每次调用都使用相同的“预计算”值。
So what you are trying to achieve would not work so simply because default parameter values are computed only once at the function definition, not at every call.因此,您尝试实现的目标不会那么简单,因为默认参数值仅在函数定义时计算一次,而不是在每次调用时计算。
Instead, you can set all default parameter values to None
and test for this value in the body of the function:相反,您可以将所有默认参数值设置为
None
并在函数体中测试此值:
def func(a, b, c, d = 0, e = [], f = None, g = None, h = None):
f = b if f == None else f
g = c if g == None else g
h = a if h == None else h
Thank you for the quick response! 谢谢你的快速反应! You´re totally right with the evaluation of the default parameters.
您对默认参数的评估完全正确。 Since I asked my question knowing that already I conclude that python leaves me without sneaky shorthands except the python if-else-shorthand you just used?
自从我知道我已经问过我的问题后,我就得出结论,除您刚刚使用的python if-else-shorthand之外,python使我没有偷偷摸摸的速记吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.