Implementing a decorator to limit setters

2019-02-18 10:50发布

问题:

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?

回答1:

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



标签: python oop