37
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Propertyデコレータを使う?

Posted at

Pythonでpropertyを定義するとき,大部分のサンプルは以下のようになっている.

property1
class Prop1(object):

    @property
    def x(self):
        '''x property'''
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

ただ,これpropertyデコレータで指定できるのはgetterのみで,
以下のようにdeleterにpropertyデコレータをつけても,deleterが定義されない. (setter/getterは定義される)

property2
class Prop2(object):

    @property
    def x(self):
        del self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.getter
    def x(self):
        return self._x

deleterはともかく,setter/getterどちらにpropertyデコレータをつけるのが正しいのか忘れそうである.
かといって,以下のように完璧にデコレータとバイバイするのも野暮ったい気がする.

property3
class Prop3(object):

    def getx(self):
        return self._x

    def setx(self, value):
        self._x = value

    def delx(self):
        del self._x

    x = property(getx, setx, delx, 'x property')

ということで,propertyデコレータは使わない(関数として使う)+getter/setter/deleterの指定にはデコレータを使用する,という書き方はどうだろう.

property4
class Prop4(object):

    x = property(doc='x property')

    @x.setter
    def x(self, value):
        self._x = value

    @x.getter
    def x(self):
        return self._x

    @x.deleter
    def x(self):
        del self._x

ただ,ネット上のソースコードを見た感じ,普通にgetterにpropertyデコレータをつける書き方が多数派のように見える...

37
40
2

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
37
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?