[英]how to pass a keyword to the function to use the default argument
What should I pass to use the default value for "name"? 我应该传递什么来使用“名称”的默认值? I do not want to explicitly pass 'lisa' since it is the default argument and the user might not be aware.
我不想显式传递'lisa',因为它是默认参数,用户可能不知道。 But if I pass an variable "name", I have to use a if else clause to pass nothing to the function in order to print"lisa".
但是如果我传递一个变量“name”,我必须使用if else子句来传递函数才能打印“lisa”。
def print_name(name='lisa'):
print name
if name != '':
print_name(name)
else:
print_name() # print lisa
What you probably want here is to make the function a bit more complicated: 你可能想要的是使函数更复杂:
def print_name(name=None):
if not name:
name='lisa'
print name
… so you can make calling it a lot simpler: ...所以你可以简单地调用它:
print_name(name)
That if not name:
will be true whenever name
is anything falsey—whether that's the default value of None
, or an empty string. if not name:
只要name
是任何假的,都将为真 - 无论是默认值None
还是空字符串。 That may not be exactly what you want—maybe you want to explicitly set the default value to ''
and check if name == '':
, for example—but it's usually a good first guess. 这可能不是你想要的 - 也许你想明确地将默认值设置为
''
并检查if name == '':
例如 - 但它通常是一个很好的第一个猜测。
So: 所以:
>>> name = ''
>>> print_name(name)
lisa
>>> name = 'alis'
>>> print_name(name)
alis
… but you can still do this: ...但你仍然可以这样做:
>>> print_name()
lisa
… which is presumably the reason you added a default value in the first place. ...这可能是您首先添加默认值的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.