Django/Python:了解函数中如何使用超级 [英] Django/Python: understanding how super is used in function

查看:39
本文介绍了Django/Python:了解函数中如何使用超级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始思考 super 是什么,以及如何在Django中基于视图的类中实现它.我试图了解以下代码中super的工作方式.有人可以为我分解一下吗?

I am just beginning to wrap my head around what super is and how it is implemented in view based classes in Django. I am trying to understand how super is working in the following code. Could someone try to break it down for me piece by piece?

from django.views.generic.detail import DetailView
from apps.app_name.models import Article

class ArticleDetailView(DetailView):
    model = Article
    template_name = 'article/show.html'

    def get_context_data(self, **kwargs):
        context = super(ArticleDetailView, self).get_context_data(**kwargs)
        return context

推荐答案

在这种情况下, super 方法将访问当前类并调用特定方法:

The super method will access to the current class and call an specific method, in this case:

super(ArticleDetailView, self)  # Access to the current class

并执行特定方法:

.get_context_data(**kwargs)

View 类中的 .get_context_data()方法,返回传递给模板的 context ( .html 文件).在这种情况下,您使用的是 DetailView ,因此您具有一些预定义的上下文,例如: object article .

The .get_context_data() method in a View class, returns the context passed to the template (.html file). In this case, you're using a DetailView, so you have some predefined context, such as: object or article.

如果仅覆盖 .get_context_data()而没有调用 .super(),则如下所示:

If you just override .get_context_data() without calling .super(), like this:

def get_context_data(self, **kwargs):
    my_context = {...}
    return my_context

您将在 DetailView 上下文中丢失预定义的变量.但是,如果要向当前 DetailView 的上下文中添加一些新变量(值),则需要原始上下文,这就是 super(ArticleDetailView,self).get_context_data(**kwargs)会给你.因此,您将以这种方式使用它:

You will lost the predefined variables in the DetailView context. But if you want to add some new variables (values) to the current DetailView's context, you need the original context, and that's what super(ArticleDetailView, self).get_context_data(**kwargs) will give you. So you will use it in this way:

def get_context_data(self, **kwargs):
    context = super(ArticleDetailView, self).get_context_data(**kwargs)
    context.update({'my_key': 'my_value'})
    return context

现在,您将能够在模板中使用自己的值,而不会丢失默认的 DetailView 的上下文值.

Now you will be able to use your own value in the template without losing the default DetailView's context values.

这篇关于Django/Python:了解函数中如何使用超级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆