物理のベンチ by mitta

学んだことを発信します。備忘録も書きます。間違いがあればコメントください。

【備忘録】Classのカッコの有無【Python】

概要

PythonのClassを使用するとき、カッコを付けないと処理が変わる。
たまに大きめの処理をするコードを1から書くことがあり、仕様を忘れて調べる羽目になっているので備忘録を残す。
ついでに、listにclassを入れた後の変更も反映されているか確認する。

カッコ有①

class TmpCls:
    a = 1

li = []
for i in range(4):
    tmp = TmpCls()   #←ここ
    print("値変更前",i,tmp.a)
    li.append(tmp)
    tmp.a = i
    print("値変更後",i,tmp.a)

for ttmp in li:
    print("for外 : a",ttmp.a)

##出力
値変更前 0 1
値変更後 0 0
値変更前 1 1
値変更後 1 1
値変更前 2 1
値変更後 2 2
値変更前 3 1
値変更後 3 3
for外 : a 0
for外 : a 1
for外 : a 2
for外 : a 3

カッコ無①

class TmpCls:
    a = 1

li = []
for i in range(4):
    tmp = TmpCls #←ここ
    print("値変更前",i,tmp.a)
    li.append(tmp)
    tmp.a = i
    print("値変更後",i,tmp.a)

for ttmp in li:
    print("for外 : a",ttmp.a)

##出力
値変更前 0 1
値変更後 0 0
値変更前 1 0
値変更後 1 1
値変更前 2 1
値変更後 2 2
値変更前 3 2
値変更後 3 3
for外 : a 3
for外 : a 3
for外 : a 3
for外 : a 3

カッコを付けない場合は文字通り「tmp=TmpCls」ってコト?

確認

class TmpCls:
    a = 1
    def __init__(self):
        self.b = 7

tmp = TmpCls
print("a =",tmp.a)
print("b =",tmp.b)
##出力
a = 1
>>例外が発生しました: AttributeError
type object 'TmpCls' has no attribute 'b' in line 8
    print("b =",tmp.b)

インスタンスも当然読めないっぽい