实现装饰器以限制设置器 [英] Implementing a decorator to limit setters

查看:61
本文介绍了实现装饰器以限制设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有少数实例变量的类,这些实例变量是通过用@someinstancevariable.setter装饰器装饰的函数设置的.我将如何确保所设置的值具有可以设置的最大值和最小值?我需要为此使用多个装饰器,还是可以使用常规的@someinstancevariable.setter装饰器并覆盖它?

解决方案

请注意,property实际上是此处发布了一种奇妙的描述符方法,具有自动的name设置...

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?

解决方案

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

这篇关于实现装饰器以限制设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆