对多个属性使用描述符(编辑:不是单个装饰器)吗? [英] Use a Descriptor (EDIT: Not a single decorator) for multiple attributes?

查看:71
本文介绍了对多个属性使用描述符(编辑:不是单个装饰器)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.5.4。对于Python来说是相当新的东西,对于昨晚的装饰器来说是全新的。如果我有一个具有多个布尔属性的类:

Python 2.5.4. Fairly new to Python, brand new to decorators as of last night. If I have a class with multiple boolean attributes:

class Foo(object):
    _bool1 = True
    _bool2 = True
    _bool3 = True
    #et cetera

    def __init__():
        self._bool1 = True
        self._bool2 = False
        self._bool3 = True
        #et cetera

有没有一种使用方法一个装饰器来检查任何布尔属性的任何设置都必须是布尔值,并为这些变量中的任何一个返回布尔值?

Is there a way to use a single decorator to check that any setting of any of the boolean attributes must be a boolean, and to return the boolean value for any requested one of these variables?

换句话说,相对于每个属性来说都是这样吗?

In other words, as opposed to something like this for each attribute?

def bool1():
    def get_boo1():
        return self._bool1
    def set_bool1(self,value):
        if value <> True and value <> False:
            print "bool1 not a boolean value. exiting"
            exit()
        self._bool1=value
    return locals()
bool1 = property(**bool1())

#same thing for bool2, bool3, etc...

我试图将其写成这样:

def stuff(obj):
    def boolx():
        def fget(self):
            return obj
        def fset(self, value):
            if value <> True and value <> False:
                print "Non-bool value" #name of object???
                exit()
            obj = value
        return locals()
    return property(**boolx())

bool1 = stuff(_bool1)
bool2 = stuff(_bool2)
bool3 = stuff(_bool3)

我:

File "C:/PQL/PythonCode_TestCode/Tutorials/Decorators.py", line 28, in stuff
    return property(**boolx())
TypeError: 'obj' is an invalid keyword argument for this function

有关如何正确执行此操作的任何指示?

Any pointers on how to do this correctly?

谢谢

Paul

推荐答案

您可以尝试使用描述符

class BooleanDescriptor(object):
    def __init__(self, attr):
        self.attr = attr

    def __get__(self, instance, owner):
      return getattr(instance, self.attr)

    def __set__(self, instance, value):
      if value in (True, False):
        return setattr(instance, self.attr, value)
      else:
        raise TypeError


class Foo(object):
    _bar = False
    bar = BooleanDescriptor('_bar')



编辑:



如S.Lott所述, python赞成鸭子输入胜过类型检查。

这篇关于对多个属性使用描述符(编辑:不是单个装饰器)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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