Skip to content Skip to sidebar Skip to footer

Implementing A Decorator To Limit Setters

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 th

Solution 1:

Note that property is really a specific implementation of a descriptor, and you can roll your own:

classValidRange(object):

    def__init__(self, name, min_, max_):
        self._min = min_
        self._max = max_
        self._name = name

    def__get__(self, instance, owner):
        returngetattr(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:

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

Post a Comment for "Implementing A Decorator To Limit Setters"