我是编程新手,希望有人能帮助澄清一些概念,以帮助我学习。
我想我理解 ** , ** 将 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/