Python 模板视图-kwargs和**kwargs
我正在通过一个教程阅读有关模板视图的内容,其中的一些代码让我有些困惑。作者使用了这个代码示例Python 模板视图-kwargs和**kwargs,python,django,Python,Django,我正在通过一个教程阅读有关模板视图的内容,其中的一些代码让我有些困惑。作者使用了这个代码示例 from django.utils.timezone import now class AboutUsView(TemplateView): template_name = 'about_us.html' def get_context_data(self, **kwargs): context = super(AboutUsView, self).get_context_data(
from django.utils.timezone import now
class AboutUsView(TemplateView):
template_name = 'about_us.html'
def get_context_data(self, **kwargs):
context = super(AboutUsView, self).get_context_data(**kwargs)
if now().weekday() < 5 and 8 < now().hour < 18:
context['open'] = True
else:
context['open'] = False
return context
如果我们已经收到了**kwargs
,那么为什么我们要用**(双启动)将其传递给超级函数呢。我想我们应该通过考试
context = super(AboutUsView, self).get_context_data(kwargs)
这是接收此呼叫的contextMixin
class ContextMixin(object):
"""
A default context mixin that passes the keyword arguments received by
get_context_data as the template context.
"""
def get_context_data(self, **kwargs):
if 'view' not in kwargs:
kwargs['view'] = self
return kwargs
据我所知,
**kwargs
的使用几乎意味着kwargs目前是一个字典,需要转换为命名值。如果这是正确的,那么当kwargs的参数实际上是**kwargs时,kwargs怎么可能是字典呢。我希望我的问题有意义。请让我知道您是否希望我对其进行重新表述。在函数声明中,**kwargs
将获取所有未指定的关键字参数并将其转换为字典
>>> test_dict = {'a':1, 'b':2}
>>> def test(**kwargs):
... print (kwargs)
...
>>> test(**test_dict)
{'b': 2, 'a': 1}
请注意,当字典对象被传递到函数(test(**test_dict)
)和函数接收时,必须使用**
转换字典对象。不可能做到以下几点:
>>> test(test_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes 0 positional arguments but 1 was given
在函数定义中,它接受多个参数,并将它们解析为一个dict。
def get_context_data(self,**kwargs):
现在,kwargs是一个dictionary对象。因此,如果您将其传递给.get\u context\u data(kwargs)
,它将只需要一个传入参数,并将其视为字典
因此,当您第二次执行
**kwargs
时,您正在将字典放大为关键字参数,这些参数将扩展为该函数调用。那么您是说您也可以使用**将多个参数转换为字典?我认为我们只能使用**从字典转换为多个参数,它是为函数保留的,而lamda用于将关键字参数转换为字典,所以遗憾的是不能。但是你可以在python3中用*like*args来打包东西。顺便问一下,你怎么知道def get_context_data(self,**kwargs):
中的kwargs实际上正在接收一个字典?@JamesFranco请参阅我的编辑:大多数情况下,这意味着接收未指定的关键字参数。
>>> test(test_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes 0 positional arguments but 1 was given
>>> def test(arg1, **kwargs):
... print (kwargs)
...
>>> test('first', a=1, b=2)
{'b': 2, 'a': 1}