Multiple optional arguments python

て烟熏妆下的殇ゞ 提交于 2019-12-05 07:59:53
devautor

**kwargs is used to let Python functions take an arbitrary number of keyword arguments and then ** unpacks a dictionary of keyword arguments. Learn More here

def print_keyword_args(**kwargs):
    # kwargs is a dict of the keyword args passed to the function
    print kwargs
    if("optarg1" in kwargs and "optarg2" in kwargs):
        print "Who needs optarg3!"
        print kwargs['optarg1'], kwargs['optarg2']
    if("optarg3" in kwargs):
        print "Who needs optarg1, optarg2!!"
        print kwargs['optarg3']

print_keyword_args(optarg1="John", optarg2="Doe")
# {'optarg1': 'John', 'optarg2': 'Doe'}
# Who needs optarg3!
# John Doe
print_keyword_args(optarg3="Maxwell")
# {'optarg3': 'Maxwell'}
# Who needs optarg1, optarg2!!
# Maxwell
print_keyword_args(optarg1="John", optarg3="Duh!")
# {'optarg1': 'John', 'optarg3': 'Duh!'}
# Who needs optarg1, optarg2!!
# Duh!

If you assign them in the call of the function you can pre-empt which parameter you are passing in.

def foo( a, b=None, c=None):
    print("{},{},{}".format(a,b,c))

>>> foo(4) 
4,None,None
>>> foo(4,c=5)
4,None,5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!