将函数输入的默认值设置为等于Python中的另一个输入 [英] Setting the default value of a function input to equal another input in Python
问题描述
考虑以下函数,它在Python中不起作用,但我将用它来解释我需要做的事情。
def exampleFunction(a,b,c = a):
...函数体...
那就是我想给变量 c
赋予与变量 a
相同的值,除非指定了替代值。上面的代码在python中不起作用。有没有办法做到这一点?
谢谢。
def exampleFunction(a,b,c = None):
如果c是None:
c = a
...函数体...
关键字参数的默认值不能是变量(如果是的话,当函数被定义时它会被转换为固定值)。常用于将参数传递给主函数:
def main(argv =无):
如果argv是None:
argv = sys.argv
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?
Thank you.
def exampleFunction(a, b, c = None):
if c is None:
c = a
...function body...
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:
def main(argv=None):
if argv is None:
argv = sys.argv
这篇关于将函数输入的默认值设置为等于Python中的另一个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!