2016-01-24 135 views
0

这是我的第一个django应用程序,我想知道是否有可能扩展所有视图的普通类。例如Django:在基于类的视图中添加另一个子类

class GeneralParent: 
    def __init__(self): 
     #SETTING Up different variables 
     self.LoggedIn = false 
    def isLoggedIn(self): 
     return self.LoggedIn 

class FirstView(TemplateView): 
    ####other stuff## 
    def get_context_data(self, **kwargs): 
     context = super(IndexView, self).get_context_data(**kwargs) 
     allLeads = len(self.getAllLeads()) 
     context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD### 

     return context 

class SecondView(FormView): 
####other stuff## 
    def get_context_data(self, **kwargs): 
     context = super(IndexView, self).get_context_data(**kwargs) 
     allLeads = len(self.getAllLeads()) 
     context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD### 

     return context 

这在django中可能吗?

回答

2

继承顺序很重要,并且要求超级级联继承的顺序。您必须考虑可能在您的__init__方法中继承传递的任何变量。

首先会调用第一个继承方法,第二个调用第一个父级的方法__init__调用super(以便调用第二个父级的__init__)。 GeneralParent必须继承自object或继承自object的类。

class GeneralParent(object): 
    def __init__(self,*args,**kwargs): 
     #SETTING Up different variables 
     super(GeneralParent,self).__init__(*args,**kwargs) 
     self.LoggedIn = false 
    def isLoggedIn(self): 
     return self.LoggedIn 

class FirstView(GeneralParent,TemplateView): 
    ####other stuff## 
    def get_context_data(self, **kwargs): 
     context = super(FirstView, self).get_context_data(**kwargs) 
     allLeads = len(self.getAllLeads()) 
     context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD### 

     return context 

class SecondView(GeneralParent,FormView): 
####other stuff## 
    def get_context_data(self, **kwargs): 
     context = super(SecondView, self).get_context_data(**kwargs) 
     allLeads = len(self.getAllLeads()) 
     context['isLoggedIn'] = ####CALL GENEREAL PARENT CLASS METHOD### 

     return context 
+0

它的工作,但为什么我的类需要继承对象? –

+1

'超'只适用于新型的类(从'object'继承) - 更多信息 - https://docs.python.org/2/glossary.html#term-new-style-class –