2017-10-08 1 views
0

私は最近、Pythonでクラスを作成して操作しようとしていましたが、私は奇妙な状況に遭遇しました。クラスのインスタンス化の変数を操作しようとすると、変更された場所の変数にのみ影響します。Pythonでは、変数自体ではなく、クラス内の変数の二項値が変わるのはなぜですか?

class test: 
    def __init__(self): 
     self.test1 = 0 
     self.location = {"test1":self.test1} 
     self.row = [self.test1] 
def change(): 
    a = test() #instantiation 
    a.location['test1'] = 1 #Changing a.test1 to 1 within a dictionary 
    print(a.test1) #Print a.test 
    print(a.location['test1']) #Print a.test1 from within the dictionary where it was changed 
    print(a.row) #Print a list also containing a.test1 
change() 

出力:例:

0 #Variable itself is unchanged 
1 #Variable in dictionary is changed 
[0] #Same variable referenced in list is unchanged as well 

は、このエラーが発生する理由とどのように私は、辞書を通してそれを変更することにより、1に等しくなるようにa.test1を変えることができますか?

+1

値を再割り当てすることで、実際の属性を再割り当てすることはありません。 –

+0

あなたのクラスの 'self.test1'への参照は何とかインスタンス変数への永続的な参照を作成していると思うようです。ではない。これらの参照は単に '0'を使うのと同じです。その理解によって、その振る舞いは今明らかでなければなりません。 –

+0

"変数をPythonの別の変数にリンクする方法はありません" - Pythonの学習 – 0TTT0

答えて

1

これは、pythonの整数が不変であるために発生します。だから、整数で操作するたびに、実際にはprevoiusオブジェクトへのポインタを作成するのではなく、新しいオブジェクトを作成します。これはeasyly次のコードでillustradedすることができます

>>> a = 0 
>>> b = a 
>>> b += 1 
>>> a, b 
(0, 1) 

しかし、あなたがリストを使用する場合、たとえば、あなたはこのようなものになるだろう:合計で

>>> a = [] 
>>> b = a 
>>> b.append(1) 
>>> a, b 
([1], [1]) 

- それとしてあなたのコードの作業をすべきだ。また、私はあなたがスニペットを以下試すことをお勧め:

あなたを生成する
class test: 
    def __init__(self): 
     self.test1 = [0] 
     self.location = {"test1": self.test1} 
     self.row = [self.test1] 


def change(): 
    a = test() #instantiation 
    a.location['test1'][0] = 1 #Changing a.test1 to 1 within a dictionary 
    print(a.test1) #Print a.test 
    print(a.location['test1']) #Print a.test1 from within the dictionary where it was changed 
    print(a.row) #Print a list also containing a.test1 

change() 

[1] 
[1] 
[[1]] 
0

何self.location [「TEST1が」]に等しくなることは自己の値を変更しない変更します.test1。

class Test: 
    def __init__(self): 
     self.test1 = 0 
     self.location = {"test1":self.test1} 
     self.row = [self.test1] 


def change(): 
    a = test() 
    a.location['test1'] = a.test1 = 1 
    a.row = [a.test1] 
    print(a.test1) 
    print(a.location['test1']) 
    print(a.row) 


change() 
0

値を辞書に割り当てるときは、self.test1の参照を置き換えます。私が知っている限り、辞書の値を「指す」方法やそれへの参照を格納する方法はありません。誰かが別のことを知っているなら、私に教えてください。

関連する問題