簡體   English   中英

django中基於類的視圖

[英]class based view in django

我試圖理解Django中基於類的視圖概念。 在此之前,我應該知道函數調用和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但表示其中沒有要定義的新內容。 相反,它將從Parent inherit其所有行為。

現在是下一個例子

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 inheritsParentChild.override消息的所有行為,因為sonChildinstance ,並且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 BAR(object):
   def baz(self,arg):
       c=10+20
       return c 

兩個基類的簡單示例

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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM