2016-08-17 92 views
0

即使在檢查了SO中提出的許多問題之後,我仍然感到困惑。我有2個不同的類(2個不同的腳本)&我想繼承超類的__init__方法的參數。__init__:將__init__參數(dict)繼承到另一個類的__init__方法?

script1.py

class MainClass(): 
    def __init__(self,params): 
     self.one=params['ONE'] 
     self.two=params['TWO'] 
     self.three=params['THREE'] 
     self.four=params['FOUR'] 
     self.five=params['FIVE'] 

    def a(): 
     #--------- 
     #somecode 
     #Initializing other class's object to access it's method. 
     s=SubClass() #HERE I WANT TO PASS 'PARAMS' (WHICH IS A DICTIONARY) 
     s.method1(....) 

script2.py

class SubClass(SuperClass): 
    def __init__(self,params): 
     #Here I want all the parameters inside the 'param' in super class. 
     #(one,two,three...., etc). 
     #By checking some SO questions, I changed class SubClass() --> 
     #class Subclass(SuperClass) & below line: 
     MainClass.__init__(self,params) #But technically I don't have anything 
             #in param in subclass. 

    def method1(): 
     #some code... 

由於子類的PARAM沒有任何東西,它給了我一個錯誤:

self.one=params['ONE'] 
TypeError: 'int' object has no attribute '__getitem__' 

我不是得到:

  1. 如何以最簡單的方式訪問超類的所有參數到子類?我不想將個別參數(如self.one,self.two ..)傳遞給子類。

  2. 如果我打電話給​​裏面的第三類 - >method1 - >打電話給第三類,和傳遞'params'一樣。可能嗎?

+1

我很難理解你想要什麼。你能否提供一些代碼示例來說明如何初始化和與'SubClass'交互? – Karin

+0

什麼是'SuperClass'? –

+0

'def __init __(self,* args,** kwargs):MainClass .__ init __(self,* args,** kwargs)'? –

回答

0

這是你所需要的?

script1.py

class MainClass(): 
    def __init__(self,params): 
     # Save params for use by a 
     self.params = params 
     self.one=params['ONE'] 
     self.two=params['TWO'] 
     ... 
     self.five=params['FIVE'] 

    def a(): 
     s=SubClass(self.params) 
     s.method1(...) 

script2.py

class SubClass(SuperClass): 
    def __init__(self,params): 
     MainClass.__init__(self,params) 

    def method1(): 
     #some code... 
0

您可以通過從子類的__init__()任何和所有的非關鍵字參數給超是這樣的:

class SubClass(SuperClass): 
    def __init__(self, *params): 
     MainClass.__init__(self, *params) 
     ... 

這個想法也適用於其他方法。

+0

Dave:請閱讀[_當有人回答我的問題時該怎麼辦?_](http://stackoverflow.com/help/someone-answers)。 – martineau