2016-04-07 41 views
-2

我需要創建對象這反過來又具有內對象的系統,例如:最好的方式來創建對象的對象裏面

class A(object): 
    def __init__(self): 
     self.A = 'Message from class A' 

class B(object): 
    def __init__(self): 
     self.B = A() 

或做它用這種方式

class B(object): 

    def __init__(self): 
     self.B = A() 

    class A(object): 
     def __init__(self): 
      self.A = 'Message from class A' 

所以我可以把它弄得像

>>> C = B() 
>>> print C.B.A 
# Message from class A 

什麼是這兩個最好的選擇,或者如果有別的東西,請歡迎!

EDIT 1的代碼

class Foam(object): 
    def __init__(self, rotor, path='OpenFoamCase'): 
     self.dirs = {} 
     self.path = path 
     self.rotor = rotor 
     self.rotorObj = Rotor(rotor) 

     # OpenFoam case directories 
     self.dirs['main'] = path if path.endswith('/') else path + '/' 
     self.dirs['system'] = path + '/system/' 
     self.dirs['constant'] = path + '/constant/' 
     self.dirs['geometry'] = path + '/geometry/' 
     self.dirs['polyMesh'] = path + '/constant/polyMesh/' 
     self.dirs['triSurface'] = path + '/constant/triSurface/' 

     self.__openFoamInit() 
     self.mesh = OpenFoamBlockMesh(self) 

class OpenFoamBlockMesh(object): 
    def __init__(self, study): 
     self.airfoil_offset = 0.5 
     self.rotor_disk_length = [20, 20] 

     ... 
    def box(self): 
     ... 

currend PICE所以現在我使用它作爲:

study = Foam(rotor=rotor, path='OpenFoamCase_Tesis') 
study.mesh.airfoil_offset = 0.02 
study.mesh.rotor_disk_length = [2, 2.5] 
study.mesh.box() 
+0

pythontonic or pythonic? – jmugz3

+0

你能提供一些上下文嗎?目前還不清楚你爲什麼要這樣做。 – jonrsharpe

+0

對不起,謝謝! – efirvida

回答

1

這真的取決於你的目的。如果A類只是B的助手類,並且是簡單和小型的類,則可以使用第二種方法(內部類)。

如果類A可能用於其他類或是大類,建議使用第一種方法(簡單構圖)。

如果您提供了一個更好的現實世界問題示例,我們可能會幫助您更多。

+0

我編輯我的問題與我的代碼的一個pice這兩個更大的類 – efirvida

+0

@efirvida我建議你堅持第一種方法(班級作文) –