4

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 about ensuring that the values set have a maximum and a minimum value to which they could be set? And would I need to have multiple decorators for this or is there some way I can use the regular @someinstancevariable.setter decorator and override it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Chris vCB
  • 1,023
  • 3
  • 13
  • 28
  • It sounds like you want a custom descriptor; have you read https://docs.python.org/2/howto/descriptor.html? See e.g. http://stackoverflow.com/q/5842593/3001761 – jonrsharpe Dec 10 '14 at 14:40

1 Answers1

3

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...

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437