我试图理解django中基于类的视图概念。在此之前,我应该知道函数调用和return语句。我想知道它在下面提到的代码。我知道即将调用父类函数。应该归还什么任何人都可以用例子解释这个概念。提前谢谢。
class Foo(Bar):
def baz(self, arg):
return super(Foo, self).baz(arg)
答案 0 :(得分:3)
我用例子解释这个。
我正在创建两个类,其中一个是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()"
这会创建一个名为class
的{{1}},但表示在其中定义并不新鲜。相反,Child
将inherit
Parent
的所有行为。{/ p>
现在下一个例子
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
来自Parent
,Child.override
条消息的所有行为,因为son
是instance
Child
而且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()
答案 1 :(得分:1)
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")