Python 2.x中的默认参数混用

0 投票
1 回答
1814 浏览
提问于 2025-04-18 16:43

我正在尝试在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?

1 个回答

2

在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}

撰写回答