小白一枚,在公司python项目里看到两段super方法的代码
class AccountLoginMixin(object):
#todo
def get_context_data(self, **kwargs):
context = super(AccountLoginMixin, self).get_context_data(**kwargs)
context['uid'] = self.uid
context['email'] = self.email
context['username'] = self.username
context['menu'] = self.get_menu()
context['menuActive'] = self.get_menu_active()
context['openMenu'] = self.openMenu
return context
class LoginView(TemplateView):
template_name = 'accounts/login.html'
#todo
def get(self, request, *args, **kwargs):
return super(LoginView, self).get(request, *args, **kwargs)
1、在以上两段代码里看不到解决了什么继承问题,还是我的理解问题?
常规的实例如下,比较好理解:
普通继承
『代码』
[python]view plaincopy
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print'Parent'
def bar(self,message):
print message, 'from Parent'
class FooChild(FooParent):
def __init__(self):
FooParent.__init__(self)
print'Child'
def bar(self,message):
FooParent.bar(self,message)
print'Child bar function.'
printself.parent
if __name__=='__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
super继承
『代码』
[python]view plaincopy
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print'Parent'
def bar(self,message):
print message,'from Parent'
class FooChild(FooParent):
def __init__(self):
super(FooChild,self).__init__()
print'Child'
def bar(self,message):
super(FooChild, self).bar(message)
print'Child bar fuction'
printself.parent
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
网上的例子都是这个样子,没觉得难理解啊。。。。 一到了具体项目里就晕了菜。
2、分别在两个地方看到super 的解释:
X1:super 是用来解决多重继承问题,直接用类名调用父类方法。
X2:super(B, self).func的调用并不是用于调用当前类的父类的func函数。
摘抄的,有些矛盾。。。顿时神经混乱了阿衰。。。
遇事不决看文档 https://docs.python.org/3/library/functions.html#super
如果一个类继承自多个父类,super可以选择调用特定父类的方法。
这段代码是官方文档上摘下来的,可能你摘抄的内容有上下语境