変数参照するとき、インスタンスに変数がなければクラス変数を探しにいきます。
代入は、インスタンスに代入します。
その様子を図にして、Qiitaのコメントに書いておきました。
https://qiita.com/msssgur/items/12992fc816e6adf32cff#comment-9244f5c1b6d7e194d59d
self.common_var = value
は、インスタンスの中に個別の common_var 変数を作って代入します。
self.common_var.append(value)
は
var = self.common_var
var.append(value)
と2段階に処理していて、self.common_var
でオブジェクトを取り出して、取り出されたオブジェクトに対して value
を append
します。
インスタンス変数には common_var
がないので、クラス変数の中から common_var
を取り出し、クラス変数の中のリストオブジェクトに value
が追加されます。
クラス変数辞書とインスタンス変数辞書を、代入前と代入後でprintして比較してみてください。
質問の下側のクラスでの確認:
python
1class TestClass(object):
2 common_var = []
3 def get_variable(self):
4 return self.common_var
5 def set_variable(self, value):
6 self.common_var.append(value)
7
8tc1 = TestClass()
9tc2 = TestClass()
10print("TestClass variables:", vars(TestClass))
11print("tc1 variables:", vars(tc1))
12print("tc2 variables:", vars(tc2))
13tc1.set_variable("Set Variable")
14print(tc2.common_var)
15print("TestClass variables:", vars(TestClass))
16print("tc1 variables:", vars(tc1))
17print("tc2 variables:", vars(tc2))
実行結果
python
1TestClass variables: {'__module__': '__main__',, 'get_variable': <function TestClass.get_variable at 0x6fffffd0d730>, 'set_variable': <function TestClass.set_variable at 0x6fffffd0d7b8>, '__dict__': <attribute '__dict__' of 'TestClass' objects>, '__weakref__': <attribute '__weakref__' of 'TestClass' objects>, '__doc__': None
2 'common_var': []}
3tc1 variables: {}
4tc2 variables: {}
5['Set Variable']
6TestClass variables: {'__module__': '__main__', 'get_variable': <function TestClass.get_variable at 0x6fffffd0d730>, 'set_variable': <function TestClass.set_variable at 0x6fffffd0d7b8>, '__dict__': <attribute '__dict__' of 'TestClass' objects>, '__weakref__': <attribute '__weakref__' of 'TestClass' objects>, '__doc__': None,
7 'common_var': ['Set Variable']}
8tc1 variables: {}
9tc2 variables: {}
クラス変数とインスタンス変数の両方を定義する:
python
1class TestClass(object):
2 common_var = [] # クラス変数
3
4 def __init__(self):
5 self.common_var = [] # インスタンス変数
6
7 def get_variable(self):
8 return self.common_var
9
10 def set_variable(self, value):
11 self.common_var.append(value)
12
13tc1 = TestClass()
14tc2 = TestClass()
15TestClass.common_var.append("Set Class Variable")
16tc1.set_variable("Set Instance Variable 1")
17tc2.set_variable("Set Instance Variable 2")
18print(TestClass.common_var)
19print(tc1.common_var)
20print(tc2.common_var)
実行結果
python
1['Set Class Variable']
2['Set Instance Variable 1']
3['Set Instance Variable 2']
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/01/12 12:26
2020/01/12 12:31 編集
2020/01/12 12:37
2020/01/12 12:44 編集
2020/01/12 12:45
2020/01/12 12:53
2020/01/12 13:00 編集
2020/01/12 12:58
2020/01/12 13:00
2020/01/12 13:02 編集
2020/01/12 13:04 編集
2020/01/12 13:07
2020/01/12 13:08
2020/01/12 13:09
2020/01/12 13:19
2020/01/12 13:49
2020/01/12 13:52
2020/01/12 13:56 編集
2020/01/12 15:11 編集
2020/01/13 00:33 編集
2020/01/13 00:50 編集
2020/01/13 00:50
2020/01/13 00:57 編集
2020/01/13 00:57