2016-11-29 4 views
0

内の変数にアクセスする多層Pythonのクラスを作成し、私は例えばのように、クラス内のクラスを作成しようとしている(とど)い:のPython 2.7では、各レイヤ

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を持っていますが、最終的に私たちは両方ともオブジェクトを作成します。 –