There is no solution, but you can try something like this:
def defprop(name): def getter(self): return getattr(self, name) return property(getter) class C(object):
This does not save you from many keystrokes, but you still have to duplicate the attribute name. In addition, it is less explicit.
Update: With a little thought, I came up with a descriptor-based hacker trick (disclaimer: this is only for demonstration, I do not mean that it is good practice if you have no damn good reason to do this):
class with_default_getter(object): def __init__(self, func): self._attr_name = '_{0.__name__}'.format(func) self._setter = func def __get__(self, obj, type): return getattr(obj, self._attr_name) def __set__(self, obj, value): return self._setter(obj, value)
Using:
class C(object): @with_default_getter def my_property(self, value): print 'setting %s' self._my_property = value >>> c = C() >>> c.my_property = 123 setting 123 >>> c.my_property 123
This is almost the same as @georg suggests, just expands the implementation to descriptors.
bereal
source share