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?
Sure, make a custom descriptor as per the concepts clearly explained in this doc:
and then just use it: