繁体   English   中英

在Python 2.x中混合默认参数

[英]Mixing default arguments in Python 2.x

我正在尝试在Python 2.7中混合使用默认关键字参数,位置参数和关键字参数。 从以下代码中,我希望profile=='system'args==(1,2,3)kwargs={testmode: True}

def bla(profile='system', *args, **kwargs):
    print 'profile', profile
    print 'args', args
    print 'kwargs', kwargs


bla(1, 2, 3, testmode=True)

我得到的是:

profile 1
args (2, 3)
kwargs {'testmode': True}

可以在Python 2.7中完成此操作,还是需要Python 3.x?

在Python2中:

def bla(*args, **kwargs):
    profile = kwargs.pop('profile', 'system')
    print 'profile', profile
    print 'args', args
    print 'kwargs', kwargs

在Python3中,可以定义仅关键字参数

def bla(*args, profile='system', **kwargs):
    print('profile', profile)
    print('args', args)
    print('kwargs', kwargs)

调用bla(1, 2, 3, testmode=True)产生

profile system
args (1, 2, 3)
kwargs {'testmode': True}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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