propertyの使い方を知ったのでまとめました.
pythonの標準ライブラリを参照しました.
機能
ライブラリにあるとおり,@propertyには3つの機能がある.
1.@property :propertyが呼び出されるとき実行
2.@名前.setter :propertyに代入されるとき実行
3.@名前.deleter :propertyが削除されるとき実行
class C:
def __init__(self):
self._x = 1
@property
def x(self):
処理 1
@x.setter
def x(self, v):
処理 2
@x.deleter
def x(self):
処理 3
一般的に説明で見られるのは以下のようなコード
class C:
def __init__(self):
self._x = 1
@property
def x(self):
return self._x
@x.setter
def x(self, v):
self._x = v
@x.deleter
def x(self):
del self._x
# インスタンス生成
c = C()
# print(処理 1 の戻り値)
print(c.x)
# 処理 2
c.x = 2
print(c.x)
# 処理 3
del c.x
print(c.x)
実行結果
1
2
Traceback (most recent call last):
File "test.py", line 49, in <module>
print(c.x)
File "test.py", line 32, in x
return self._x
AttributeError: 'C' object has no attribute '_x'
上のように使うと意図された処理が実行される.
他の使い方
処理1,2,3 は必ずしも代入や削除のような内容である必要はない.
単純にpropertyに対して値を返す要求があれば,「処理 1」が実行されるし,propertyに代入する処理が出てくれば,「処理 2」が実行されるし,delの構文が存在すれば「処理 3」が行われる.
そのため,下のようなpropertyにした場合,
class C:
def __init__(self):
self._x = 1
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
#del self._x
print("削除しませぇぇぇぇん!")
c = C()
print(c.x)
del c.x
print(c.x)
del c._x
print(c.x)
下のように削除されたと思いきや,削除されていないという現象を作成可能.ただし,直接メンバ変数を削除しにかかると当然削除される(悲しい).
1
削除しませぇぇぇぇん!
1
Traceback (most recent call last):
File "test.py", line 25, in <module>
print(c.x)
File "test.py", line 7, in x
return self._x
AttributeError: 'C' object has no attribute '_x'
まとめ
propertyによって,メンバ変数に対する代入や削除に対して適当な処理を与えることが可能.開発の現場では主に意図しない変数の代入を避けるために以下のようにエラーを出すような処理にしているようです.
@x.setter
def x(self, value):
raise ValueError()