2016-07-27 4 views
1

こんにちは私はcでプログラミングを見つめていて、私はconld'ntがPythonで値の範囲を理解しています。ここPythonの値の範囲が混乱しています

は私のコード

class ScenarioEnvironment(): 
    def __init__(self): 
     print(self) 

class report(): 
    config = ScenarioEnvironment() 
    def __init__(self): 
     self.config = ScenarioEnvironment() 

で何が起こるのinitで設定し、設定を渡しますか()?

と私は値のスコープはどのクラスが貴重なものになるのだろうか?

+0

設定をレポートクラスに渡すことはありません。これは、他のクラスコンストラクタへのパラメータがないために実行されません –

答えて

3

あなたはクラス属性とインスタンスオブジェクトの属性の違いを知っておく必要があります。 たぶん、これらのコードがお手伝いします:

class TestConfig1(object): 
    config = 1 

    def __init__(self): 
     self.config = 2 


class TestConfig2(object): 
    config = 1 

    def __init__(self): 
     self.config2 = 2 

if __name__ == "__main__": 
    print TestConfig1.config 
    t = TestConfig1() 
    print t.config 
    t2 = TestConfig2() 
    print t2.config 
    print t2.config2 

より多くのあなたは、Pythonのブログを参照してくださいすることができます。 click here

0

あなたの質問は少しあいまいなようだので、私はあなたのコードを修正/コメントます:

class ScenarioEnvironment(): 
    def __init__(self,x): 
     self.x = x # Assigning instance variable x to constructor parameter x. 
     print(self) # You're printing the object instance. 

class report(): 
    # Static variable shared amongst all classes. 
    config = ScenarioEnvironment(None) # Assigned to new instance of ScenarioEnvironment. 

    def __init__(self): 
     # No argument, must pass one (None). 
     # self.config is to a new ScenarioEnvironment instance. 
     self.config = ScenarioEnvironment(None) 

は、クラスを試してみることができます。

出力:

s = ScenarioEnvironment(None) 
r = report() 
>>> <__main__.ScenarioEnvironment instance at 0x026F4238> 
>>> <__main__.ScenarioEnvironment instance at 0x026F4300> 
>>> <__main__.ScenarioEnvironment instance at 0x026F4350> 
関連する問題