python - Defining setter in a shorter way -
currently when want define setter , leave getter alone this:
@property def my_property(self): return self._my_property @my_property.setter def my_property(self, value): value.do_some_magic() self._my_property = value
is there way make shorter? i'd skip part same:
@property def my_property(self): return self._my_property
you can make decorator auto-creates getter, following underscores convention:
def setter(fn): def _get(self): return getattr(self, '_' + fn.__name__) def _set(self, val): return fn(self, val) return property(_get, _set)
or more concisely, if style more:
def setter(fn): return property( lambda self: getattr(self, '_' + fn.__name__), fn)
usage:
class x(object): @setter def my_property(self, value): self._my_property = value + 1 x = x() x.my_property = 42 print x.my_property # 43
Comments
Post a Comment