python可选参数传递方式,多个可选参数python

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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值