2016-11-29 60 views
0

在Python 2.7,我試圖創建類中的類(等),例如像:創建每一層內多層Python類可以訪問變量

class Test(object): 

    def __init__(self, device_name): 
     self.device_name = device_name 

    class Profile(object): 
     def __init__(self, x1, x2): 
      self.x1 = x1 
      self.x2 = x2 

    class Measurement(object): 
     def __init__(self, x1, x2): 
      self.x1 = x1 
      self.x2 = x2  

使用這種分層來創建對象,我需要能夠分配,在任何一層訪問任何變量,例如像:

test1 = Test("Device_1") 
Test.Profile(test1, 10, 20) 
Test.Measurement(test1, 5, 6) 

print test1.Profile.x1 
print test1.Measurement.x1 

還應當指出的是,我需要從一個文本文件中獲取的數據來加載類。

我認爲使用類將是實現這一目標的最佳方式,但我很樂意聽到任何其他想法。

+1

爲什麼你創建的類中的類? –

+0

你的問題是什麼? –

+0

您可以將Profile和Measurement類分開文件,並從Test類返回這些類的實例。你不需要做那個嵌套。 – emKaroly

回答

0

我的版本/解決方案class scopes

class Test(object): 

    def __init__(self, device_name): 
     self.device_name = device_name 

    class Profile(object): 
     def __init__(self, x1, x2): 
      self.x1 = x1 
      self.x2 = x2 

    class Measurement(object): 
     def __init__(self, x1, x2): 
      self.x1 = x1 
      self.x2 = x2 

test1 = Test("Device_1") 
prof = test1.Profile(10, 20) 
meas= test1.Measurement(5, 6) 

print (prof.x1) 
print (meas.x1) 

>>> 10 
>>> 5 
0

雖然我不知道爲什麼你要嵌套類,只要你想這會做完全。如果你看一下這個例子,一定要注意語法的變化。

class Test(object): 
    class Profile(object): 
     def __init__(self, x1, x2): 
      self.x1 = x1 
      self.x2 = x2 

    class Measurement(object): 
     def __init__(self, x1, x2): 
      self.x1 = x1 
      self.x2 = x2 

    def __init__(self, device_name): 
     self.device_name = device_name 
     self.profile = None 
     self.measurement = None 

    def make_profile(self, a, b): 
     self.profile = self.Profile(a, b) 

    def make_measurement(self, a, b): 
     self.measurement = self.Measurement(a, b) 

test1 = Test("Device_1") 
test1.make_profile(10, 20) 
test1.make_measurement(5, 6) 

print (test1.profile.x1) 
print (test1.measurement.x1) 

輸出:

10 
5 
+0

真的需要額外的方法嗎? –

+0

在你的解決方案中,你創建了單獨的對象,而我的所有對象都在同一個對象中。理論上你可以傳入原始構造函數中的所有參數,但似乎並不像他想要的那樣。 – Navidad20

+0

你有@property這種情況下,但最終我們都創建對象.... –