python super函数在django模型中的使用 [英] use of python super function in django model
问题描述
这是我正在阅读的 django 教程中的一些代码.我以前从未在 python 中遇到过 super 函数,这里使用的方式与我在网上看到的示例不同.即,通常当您使用 super 时,您不是有多个类吗?它在最后一行:super(Snippet, self).save(force_insert, force_update)
您能否准确解释一下那里发生了什么以及编写它的另一种方法是什么.好像 save 方法在这里调用了自己?
Here's some code in a django tutorial that I'm going through. I've never come across the super function in python before and the way it's used here is different from the examples I've seen online. I.e., usually when you use super, don't you have multiple classes? It's in the last line: super(Snippet, self).save(force_insert, force_update)
Could you explain exactly what's going on there and what would be an alternative way to write that. It just seems like the save method is calling itself here?
class Snippet(models.Model):
title = models.CharField(max_length=255)
language = models.ForeignKey(Language)
author = models.ForeignKey(User)
description = models.TextField()
description_html = models.TextField(editable=False)
code = models.TextField()
highlighted_code = models.TextField(editable=False)
tags = TagField()
pub_date = models.DateTimeField(editable=False)
updated_date = models.DateTimeField(editable=False)
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.title
def save(self, force_insert=False, force_update=False):
if not self.id:
self.pub_date = datetime.datetime.now()
self.updated_date = datetime.datetime.now()
self.description_html = markdown(self.description)
self.highlighted_code = self.highlight()
super(Snippet, self).save(force_insert, force_update)
推荐答案
super(Snippet, self)
使 Python 在 MRO 类的 self(即 self.__class__.mro()
用于 next 列在 Snippet
之后的类.它返回一个 super
对象,该对象充当该类的代理.也就是说,调用 super
上的方法> 对象就像在类上调用该方法一样.
super(Snippet, self)
causes Python to look in the MRO of the class of self (i.e. self.__class__.mro()
for the next class listed after Snippet
. It returns a super
object which acts as a proxy for that class. That is, calling a method on the super
object acts like calling that method on the class.
super(Snippet, self).save(...)
调用该类的 save
方法,将 self
绑定到第一个参数.
super(Snippet, self).save(...)
calls that class's save
method, with self
bound to the first argument.
所以super(Snippet, self).save(...)
不会调用Snippet
的save
方法;它将调用其他类的 save
方法.人们很容易认为这个其他类"是 Snippet
的父类"或超类",也就是说,models.Model
,但这可能不是真的,这样理解 super
是绝对错误的.super(Snippet, self)
最终代表哪个类取决于 self
,特别是它的类的 MRO.
So super(Snippet, self).save(...)
will not call Snippet
's save
method; it will call some other class's save
method. It is tempting to think this "other class" is the "parent class" or "superclass" of Snippet
, that is,
models.Model
, but that may not be true and it is absolutely wrong to apprehend super
this way. Which class super(Snippet, self)
ultimately represents depends on self
and in particular its class's MRO.
可以在 这里.
这篇关于python super函数在django模型中的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!