Python 如何使用命名参数列表调用函数?
考虑以下功能:Python 如何使用命名参数列表调用函数?,python,Python,考虑以下功能: def test(first, second = None, third = None): print first print second print third test('one', third = 'three') 我想用我用一些逻辑非工作伪代码建立的列表来调用它: arguments = ['one'] arguments.append(third = 'three') test(arguments) 如何做到这一点?这 argument
def test(first, second = None, third = None):
print first
print second
print third
test('one', third = 'three')
我想用我用一些逻辑非工作伪代码建立的列表来调用它:
arguments = ['one']
arguments.append(third = 'three')
test(arguments)
如何做到这一点?这
arguments.append(third = 'three')
这是不可能的。使用字典:
args = {"third":"three"}
test("one", **args)
输出:
one
None
three
编辑:我看不出对位置参数使用单独的结构有什么意义。只要只有一个这样的参数,*[one]就不比1短。使用列表表示位置参数,使用字典表示命名参数。c、 f
首先,你不能这样做
arguments.append(third = 'three')
这不是有效的python指令。你在找的是一本字典
arguments = {'first': 'one'}
arguments['third'] = 'three'
好消息是,在python中,可以通过传递位置参数列表和/或命名参数列表来调用函数。你会用魔法的
*运算符允许您以列表形式传递位置参数
**运算符允许您将命名参数作为字典传递
按照您的示例,您将执行以下操作:
pargs = ['one']
kwargs = {'third': 'three'}
test(*pargs, **kwargs)
dictionary是比listit的*[one]更好的选项,而且它实际上是有用的:在这种情况下,参数由动态源(如CLI或web服务)提供。您事先不知道将传递多少个位置参数和命名参数:对不起,输入错误。我毫不怀疑这种语法是有用的。但就目前的问题而言,这感觉有点过头了。好吧,我还认为**{third:three}并不比third='three'短,它完全是无用的评论:
pargs = ['one']
kwargs = {'third': 'three'}
test(*pargs, **kwargs)