python - 对如何使用 **kwarg 感到困惑

标签 python keyword-argument

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

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

虽然我不太清楚为什么我需要使用 ** 两次。具体来说,为什么我需要显式地传入 **param(相对于 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?

最佳答案

诀窍在于,虽然符号 (**) 相同,但 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-only函数做自动解包,如果函数有任何显式参数(或关键字参数) ) Python 将无法自动解压字典。

关于python - 对如何使用 **kwarg 感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17616737/

相关文章:

python - 修改某些 pandas 数据框列,将更改应用于整个原始数据框

python - GAE-AppEngine-DeadlineExceededError : Deadline exceeded while waiting for HTTP response from URL:

python - 将 concurrent.futures.ThreadPoolExecuter() 与 kwargs 一起使用

python - 创建 GAE 实体时遇到问题

python-3.x - 传递一个集合来打印,在Python 3中使用分隔符打印?

python - 仅在代码的某些部分记录打印两次

python - 为什么我要在 pandas 中复制数据框

python - 使用 Python 发送电子邮件并在主题行中包含变量

Python:使用for循环创建未知数量的变量

python - 如何在 python 中将可变长度参数与关键字参数结合起来?