Implementing a decorator to limit setters

后端 未结 1 461
慢半拍i
慢半拍i 2021-01-13 15:51

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

相关标签:
1条回答
  • 2021-01-13 16:32

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

    0 讨论(0)
提交回复
热议问题