2016-01-24 169 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 –