【发布时间】:2012-02-23 14:37:59
【问题描述】:
我正在使用类装饰器,但我不明白如何使用 setattr 设置属性,这是我的代码:
def cldecor(*par):
def onDecorator(aClass):
class wrapper:
def __init__(self, *args):
self.wrapped = aClass(*args)
def __getattr__(self, name):
return getattr(self.wrapped, name)
def __setattr__(self, attribute, value):
if attribute == 'wrapped':
self.__dict__[attribute] = value
else:
setattr(self.wrapped, attribute, value)
return wrapper
return onDecorator
@cldecor('data','size')
class Doubler:
def __init__(self,label,start):
self.label = label
self.data = start
def display(self):
print('{0} => {1}'.format(self.label, self.data))
但是当我这样做时:
if __name__ == "__main__":
X = Doubler('X is ', [1,2,3])
X.xxx = [3,4,9]
print(X.xxx)
X.display()
我有这个输出:
[3, 4, 9]
X is => [1, 2, 3]
我该怎么做才能有这个输出?
[3, 4, 9]
X is => [3, 4, 9]
【问题讨论】:
-
或许能解释一下你认为这应该达到什么目的?
-
*par在您的代码中做了什么?你让它不用... -
您发布的代码不会生成您显示的输出。我得到的输出是
'[3, 4, 9]\n X is => [1, 2, 3]' -
好的,我改变了我的输出,但问题仍然存在
-
@fege,当您编写或编辑问题时,不要弄乱缩进。选择您的代码,然后使用编辑框顶部的
{}按钮对其进行格式化。它会为你做一切。