传递一份狼人名单?

为了简洁起见,我可以将 kwargs 列表传递给一个方法吗:

def method(**kwargs):
#do something


keywords = (keyword1 = 'foo', keyword2 = 'bar')
method(keywords)
91728 次浏览

是的,你这样做:

def method(**kwargs):
print kwargs


keywords = {'keyword1': 'foo', 'keyword2': 'bar'}
method(keyword1='foo', keyword2='bar')
method(**keywords)

在 Python 中运行这个命令可以确认产生相同的结果:

{'keyword2': 'bar', 'keyword1': 'foo'}
{'keyword2': 'bar', 'keyword1': 'foo'}

Do you mean a dict? Sure you can:

def method(**kwargs):
#do something


keywords = {keyword1: 'foo', keyword2: 'bar'}
method(**keywords)

As others have pointed out, you can do what you want by passing a dict. There are various ways to construct a dict. One that preserves the keyword=value style you attempted is to use the 迪克特 built-in:

keywords = dict(keyword1 = 'foo', keyword2 = 'bar')

请注意 dict的多功能性; 所有这些都产生相同的结果:

>>> kw1 = dict(keyword1 = 'foo', keyword2 = 'bar')
>>> kw2 = dict({'keyword1':'foo', 'keyword2':'bar'})
>>> kw3 = dict([['keyword1', 'foo'], ['keyword2', 'bar']])
>>> kw4 = dict(zip(('keyword1', 'keyword2'), ('foo', 'bar')))
>>> assert kw1 == kw2 == kw3 == kw4
>>>

因此,当我来到这里时,我正在寻找一种在一个函数中传递多个 * * kwargs 的方法,以便以后在进一步的函数中使用。因为毫不奇怪,这种方法行不通:

def func1(**f2_x, **f3_x):
...

通过一些自己的“实验性”编码,我找到了显而易见的方法:

def func3(f3_a, f3_b):
print "--func3--"
print f3_a
print f3_b
def func2(f2_a, f2_b):
print "--func2--"
print f2_a
print f2_b


def func1(f1_a, f1_b, f2_x={},f3_x={}):
print "--func1--"
print f1_a
print f1_b
func2(**f2_x)
func3(**f3_x)


func1('aaaa', 'bbbb', {'f2_a':1, 'f2_b':2}, {'f3_a':37, 'f3_b':69})

This prints as expected:

--func1--
aaaa
bbbb
--func2--
1
2
--func3--
37
69