Help us understand the problem. What is going on with this article?

Propertyデコレータを使う?

More than 5 years have passed since last update.

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デコレータをつける書き方が多数派のように見える...

FGtatsuro
I'm mainly interested in Python, Objective-C, Java, Android.
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした