python - Function to define the @property for multiple attributes -
i trying make function takes in variable number of attributes class instance , redefines them @property, giving attribute getter , setter.
i want achieve this:
@property def x(self): return self._x @x.setter def x(self, value): self._x = value @property def dx(self): return self._dx @dx.setter def dx(self, value): self._dx = value @property def dy(self): return self._dy @dy.setter def dy(self, value): self._dy = value
by doing this:
decorate_these_attributes(self.x, self.dx, self.dy)
here have far:
def decorate_these_attributes(self, *args): def attr_set(attr, val): attr = val attr in args: attr_get = lambda: attr attr = property(attr_get, attr_set)
as of now, when call function, doesn't anything. ideas of doing wrong?
you use class decorator or metaclass things this:
def apply_property(cls): def make_getter(name): def getter(self): return getattr(self, name) return getter def make_setter(name): def setter(self, val): setattr(self, name, val) return setter f in cls.fields: getter = make_getter('_' + f) setter = make_setter('_' + f) setattr(cls, f, property(getter, setter)) return cls @apply_property class point: fields = ['x', 'y', 'z']
i'm assuming have more complex example in mind. if that's not case, think can use plain attributes, no need properties. , in cases need different behavior different properties, try searching "python descriptor".
Comments
Post a Comment