简体   繁体   中英

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. 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".

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. 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.


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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM