多个可选参数python [英] Multiple optional arguments python

查看:267
本文介绍了多个可选参数python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个带有几个可选参数的函数,如下所示:

So I have a function with several optional arguments like so:

def func1(arg1, arg2, optarg1=None, optarg2=None, optarg3=None):

Optarg1& optarg2通常一起使用,如果指定了这两个参数,则不使用optarg3.相反,如果指定了optarg3,则optarg1&不使用optarg2.如果它是一个可选参数,则函数很容易知道"要使用的参数:

Optarg1 & optarg2 are usually used together and if these 2 args are specified then optarg3 is not used. By contrast, if optarg3 is specified then optarg1 & optarg2 are not used. If it were one optional argument it'd be easy for the function to "know" which argument to use:

if optarg1 != None:
    do something
else:
    do something else 

我的问题是,当存在多个可选参数且并非始终指定所有可选参数时,如何告诉"该函数使用哪个可选参数?用** kwargs解析参数是可行的方法吗?

My question is how to I "tell" the function which optional argument to use when there's multiple optional arguments and not all of them are always specified? Is parsing the arguments with **kwargs the way to go?

推荐答案

** kwargs用于让Python函数接受任意数量的关键字参数,然后**解压缩关键字参数字典. 在此处了解更多信息

**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!

这篇关于多个可选参数python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆