Can I add parameters to a python property to reduce code duplication?
python
Solution
Sure, make a custom descriptor as per the concepts clearly explained in this doc:
class JonProperty(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, objtype):
return getattr(obj, self.name)
def __set__(self, obj, val):
setattr(obj, self.name, float(val))
and then just use it:
class Vector(object):
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
x = JonProperty('_x')
y = JonProperty('_y')
z = JonProperty('_z')
Problem
I have a the following class: ``` class Vector(object): def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z def _getx(self): return self._x def _setx(self, value): self._x = float(value) x = property(_getx, _setx) def _gety(self): return self._y def _sety(self, value): self._y = float(value) y = property(_gety, _sety) def _getz(self): return self._z def _setz(self, value): self._z = float(value) z = property(_getz, _setz) ``` The three getters and setters are all identical except for the object property they are modifying (x, y, z). Is there a way that I can write one get and one set and then pass the variable to modify so that I don't repeat myself?