class 基于 django 的视图

class based view in django

我正在尝试理解 Django 中基于 class 的视图概念。在那之前我应该​​知道函数调用并且 return statement.I 想知道它做了什么我在下面的代码中提到了。我知道即将调用 parent class 函数。它应该是什么return。任何人都可以用例子来解释这个概念。提前致谢。

class Foo(Bar):
  def baz(self, arg):
    return super(Foo, self).baz(arg)

我用例子来解释这个。

我正在创建两个 类,其中一个是 inheriting 来自另一个。

class Parent(object):

    def implicit(self):
        print "PARENT implicit()"

class Child(Parent):
    pass

dad = Parent()
son = Child()

>>>dad.implicit()
>>>son.implicit()
"PARENT implicit()"
"PARENT implicit()"

这会创建一个名为 Childclass,但表示其中没有新内容要定义。相反,它将 inherit 所有来自 Parent.

的行为

现在下一个例子

class Parent(object):

    def override(self):
        print "PARENT override()"

class Child(Parent):

    def override(self):
        print "CHILD override()"

dad = Parent()
son = Child()

>>>dad.override()
>>>son.override()
"PARENT override()"
"CHILD override()"

尽管 Child inherits 来自 ParentChild.override 消息的所有行为,因为 son 是 [=15= 的 instance ] 和 Child 通过定义自己的版本

来覆盖该函数

现在下一个例子,

class Parent(object):

    def altered(self):
        print "PARENT altered()"

class Child(Parent):

    def altered(self):
        print "CHILD, BEFORE PARENT altered()"
        super(Child, self).altered()
        print "CHILD, AFTER PARENT altered()"

dad = Parent()
son = Child()

>>>dad.altered()
>>>son.altered()
"PARENT altered()"
"CHILD, BEFORE PARENT altered()"
"PARENT altered()"
"CHILD, AFTER PARENT altered()"

在这里我们可以找到 super(Child, self).altered(),它知道 inheritance 并将获得 Parent class。(不关心覆盖)

希望这对您有所帮助

更新。.在python3

super().altered()可以代替super(Child, self).altered()

使用

更多http://learnpythonthehardway.org/book/ex44.html

class Foo(Bar):#here Bar is your super class, you inherit  super class methods 
  def baz(self, arg):#this class method 
    return super(Foo, self).baz(arg)# here super is mentioned as  super class of Foo .baz(arg) is you call the super user method baz(arg)

所以你需要像

一样创建超级 class
class BAR(object):
   def baz(self,arg):
       c=10+20
       return c 

两个碱基的简单示例class

class bar(object):
  def baz(self, arg):
    print"this is bar class" 

class bar1(object):
  def baz1(self,arg):
    print "this is bar1 class"         
class Foo(bar,bar1):
  def baz(self, arg):
    super(Foo, self).baz1(arg)  
    super(Foo, self).baz(arg)

a=Foo()
a.baz("hai")