简体   繁体   English

通过一个kwargs列表?

[英]Passing a list of kwargs?

Can I pass a list of kwargs to a method for brevity? 我可以将kwargs列表传递给简洁方法吗? This is what i'm attempting to do: 这就是我正在尝试做的事情:

def method(**kwargs):
    #do something

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

Yes. 是。 You do it like this: 你这样做:

def method(**kwargs):
  print kwargs

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

Running this in Python confirms these produce identical results: 在Python中运行它确认这些产生相同的结果:

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

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 dict built-in: 保留您尝试的keyword=value样式的一种方法是使用内置的dict

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

Note the versatility of dict ; 注意dict的多功能性; all of these produce the same result: 所有这些产生相同的结果:

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

Do you mean a dict? 你的意思是一个字吗? Sure you can: 你当然可以:

def method(**kwargs):
    #do something

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

So when I've come here I was looking for a way to pass several **kwargs in one function - for later use in further functions. 所以当我来到这里时,我正在寻找一种方法在一个函数中传递几个** kwargs - 以后用于其他函数。 Because this, not that surprisingly, doesn't work: 因为这不奇怪,不起作用:

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

With some own 'experimental' coding I came to the obviously way how to do it: 通过一些自己的“实验性”编码,我明显地知道如何做到这一点:

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

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

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