2014-12-03 51 views
0

我有下面的代碼發生問題,因爲子對象需要參數,纔可以創建一個實例。我是否需要創建某種函數來處理創建子對象?創建一個parent.child類結構,其中的孩子有一個

我希望能夠做到:

a = parent() 
a.other('param').double(2) 
2 
a.other('param').other_class('another_param').square(4) 
16 

這是我的代碼:

class parent(object): 

    def __init__(self): 
     self.other = other_class2(self) 
     self.answer = None 

    def multiply(self,x,y): 
     self.answer = x*y 
     return x*y 

    def add(self,x,y): 
     self.answer = x+y 
     return x+y 


class other_class(object): 

    def __init__(self,parent,inputed_param): 
     self.parent = parent 
     self.input = inputed_param 

    def square(self,x): 
     self.answer = self.parent.parent.multiply(x,x) 
     return self.parent.parent.multiply(x,x) 


class other_class2(object): 

    def __init__(self,parent,inputed_param): 
     self.parent = parent 
     self.other_class = other_class(self) 
     self.input = inputed_param 

    def double(self,x): 
     self.answer = self.parent.add(x,x) 
     return self.parent.add(x,x) 

在我實際的代碼我創建一個Python包裝到一個網站,創建內的任務自動化配置文件,在每個配置文件是一個摘錄。我認爲這種樹結構將是管理所有相關例程的最佳方式。

我需要父類來維護網站的連接端,我希望parent.profile(profile_id)包含與每個配置文件相關的任務/例程。然後,我想parent.profile(profile_id).extract(extract_id)包含與每個摘錄相關的任務/例程。

回答

1

當您詢問param時,您可以構建課程。該代碼應該實現你想要的行爲。

class parent(object): 

    def __init__(self): 
     self.other = lambda param: other_class2(self,param) 
     self.answer = None 

class other_class2(object): 

    def __init__(self,parent,inputed_param): 
     self.parent = parent 
     self.other_class = lambda param: other_class(self,param) 
     self.input = inputed_param 
相關問題