LoginSignup
134
92

More than 3 years have passed since last update.

python property

Last updated at Posted at 2018-06-23

property

pythonで自分で定義したオブジェクトから値を取得したり更新したり削除したりしたい時の
動作を定義することができる機能

使ってみる

まずはpropertyを使わない場合

class NoProperty(object):
    def __init__(self, x):
        self._x = x

    def get_x(self):
        return self._x

    def set_x(self, v):
        self._x = abs(v)

    def del_x(self):
        self._x = None
実行結果
nopro = NoProperty(100)
print(nopro.get_x()) # 100

nopro.set_x(-200)
print(nopro.get_x()) # 200

nopro.del_x()
print(nopro.get_x()) # None

同じことをpropertyを使って表現

class MyProperty(object):
    def __init__(self, x):
        self._x = x

    @property # propertyの時は x.getterと同義
    def x(self):
        return self._x

    @x.setter
    def x(self, v):
        self._x = abs(v) # 更新前に何らかの処理をはさめる

    @x.deleter
    def x(self):
        self._x = None
実行結果

mypro = MyProperty(100)
print(mypro.x) # 100

mypro.x = -200
print(mypro.x) # 200

del mypro.x
print(mypro.x) # None

使わない場合と実行の仕方が違うことに注意

propertyを使って動作を制限

class MyProperty(object):
    def __init__(self, x):
        self._x = x

    @property
    def x(self):
        return self._x
実行結果
mypro = MyProperty(100)
print(mypro.x) # 100

mypro.x = -200
AttributeError # 定義されていないのでエラー

読み取り専用として使いたい時などに便利

134
92
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
134
92