混淆了如何使用** kwarg

时间:2013-07-12 14:02:41

标签: python kwargs

我是编程新手,希望有人可以帮助澄清一些概念来帮助我学习。

我想我理解**,**将kwarg转换为关键字然后传递给函数。

我不确定为什么我需要使用**两次。具体来说,为什么我需要在函数定义中明确传入** param(vs param),我将在kwarg中传递

class Main(webapp2.RequestHandler):
    def render(self, template, **kwarg):
        blah

class Test(Main):
    params = dict(a=1, b=2)
    self.render(template, params) #this doesn't work

    self.render(template, **params) 
    #this work, but I don't understand why do I need the ** again
    #when its already in the original render function?

3 个答案:

答案 0 :(得分:3)

诀窍是虽然符号(**)相同,但operator却不同:

def print_kwargs(**all_args):
    # Here ** marks all_args as the name to assign any remaining keyword args to
    print all_args

an_argument = {"test": 1}

# Here ** tells Python to unpack the dictionary
print_kwargs(**an_argument)

如果我们没有在print_kwargs的调用中显式解包我们的参数,那么Python将抛出TypeError,因为我们提供了print_kwargs不接受的位置参数。

为什么Python不能自动将字典解压缩到kwargs?主要是因为“显式优于隐式” - 而你可以**kwarg - 仅函数自动解包,如果函数有任何显式参数(或关键字参数),Python将不会能够自动解压缩字典。

答案 1 :(得分:2)

让我们说你有这样的方法......

>>> def fuct(a, b, c):
...   print a
...   print b
...   print c

并且您已经获得了发送到方法所需的参数的字典

d = {'a': 1, 'b': 2, 'c': 3}

所以通过使用**(双星号)你可以解压缩字典并发送到函数

>>> fuct(**d)
1
2
3
>>>

答案 2 :(得分:0)

因为非关键字参数使用*args。单个*将列表或元组解包为元素,两个*将dict解压缩到关键字。

相关问题