在python中,是否可以定义可覆盖的可选默认值,如果您定义该值,它不使用默认值,但如果您不使用,它会使用?
例如:
def hats(a= 'large', b= 'baseball', c= 'five dollars'):
#method stuff goes here
我知道我可以定义,a然后将默认值,但我可以以某种方式定义并拥有和使用默认值吗?bccab
比如,我可以调用方法吗hats(NULL, something, something else)
在python中,是否可以定义可覆盖的可选默认值,如果您定义该值,它不使用默认值,但如果您不使用,它会使用?
例如:
def hats(a= 'large', b= 'baseball', c= 'five dollars'):
#method stuff goes here
我知道我可以定义,a然后将默认值,但我可以以某种方式定义并拥有和使用默认值吗?bccab
比如,我可以调用方法吗hats(NULL, something, something else)
我可以以某种方式定义 c 并让 a 和 b 使用默认值吗
当然:
hats(c = 'something')
a将使用和的默认值b。
当然。调用函数时可以参考参数名称
def hats(a= 'large', b= 'baseball', c= 'five dollars'):
print a,b,c
hats(b = "football")
>>> large football five dollars
如果您传递参数但未指定名称,则参数将按顺序传递,例如:
hats("big","tennis")
>>> big tennis five dollars
以上结果仅更改了前两个参数(a 和 b)并将 c 保留为默认值。
最后,您根本不必传递任何参数:
hats()
>>> large baseball five dollars
这就是默认参数的重点。如果你传入一些东西,你传入的东西就会被使用。如果不这样做,则使用默认值。