When defining property in Python, most of the samples are as follows.
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
However, only getters can be specified with this property decorator, Even if you attach a property decorator to deleter as shown below, deleter is not defined. (Setter / getter is defined)
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
Regardless of the deleter, it's easy to forget which of the setter and getter should have the property decorator. On the other hand, it feels uncomfortable to buy bye with the decorator perfectly as follows.
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')
So, how about writing that the property decorator is not used (used as a function) + the decorator is used to specify 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
However, it feels like looking at the source code on the net, and the way of writing to add a property decorator to a getter seems to be the majority ...
Recommended Posts