I have a class with a handful of instance variables, which I set through functions decorated with the @someinstancevariable.setter
decorators. How would I go ab
Note that property
is really a specific implementation of a descriptor, and you can roll your own:
class ValidRange(object):
def __init__(self, name, min_, max_):
self._min = min_
self._max = max_
self._name = name
def __get__(self, instance, owner):
return getattr(instance, self._name)
def __set__(self, instance, value):
setattr(instance, self._name, min(self._max, max(value, self._min)))
def __delete__(self, instance):
delattr(instance, self.name)
This would be used like:
>>> class Weather(object):
... temperature = ValidRange('_temp', 0, 100)
...
>>> w = Weather()
>>> w.temperature = 120
>>> w.temperature
100
I've posted a fancier descriptor method here with automagical name
-setting...