蟒蛇 2.5.4。对 Python 来说相当新,昨晚对装饰器来说是全新的。如果我有一个具有多个布尔属性的类:
class Foo(object):
_bool1 = True
_bool2 = True
_bool3 = True
#et cetera
def __init__():
self._bool1 = True
self._bool2 = False
self._bool3 = True
#et cetera
有没有办法使用单个装饰器来检查任何布尔属性的任何设置是否必须是布尔值,并返回任何请求的这些变量之一的布尔值?
换句话说,与每个属性的类似内容相反?
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
有关如何正确执行此操作的任何指示?
谢谢,
保罗