__setattr_uu;类装饰器python
我正在使用类装饰器,但我不明白如何使用setattr设置属性,这是我的代码:__setattr_uu;类装饰器python,python,decorator,setattr,Python,Decorator,Setattr,我正在使用类装饰器,但我不明白如何使用setattr设置属性,这是我的代码: def cldecor(*par): def onDecorator(aClass): class wrapper: def __init__(self, *args): self.wrapped = aClass(*args) def __getattr__(self, name):
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]
您的
display
方法仅打印self.data
中的数据,但您已经创建了一个属性caledxxx
。当然,display
不会显示它。这项工作:
>>> X.data = [3,4,9]
>>> X.display()
X is => [3, 4, 9]
也许可以解释一下你认为这应该实现什么?在你的代码中,
*par
做了什么?您没有使用它…您发布的代码不会生成您显示的输出。我得到的输出是'[3,4,9]\n X是=>[1,2,3]'
好的,我更改了输出,但问题是remains@fege,编写或编辑问题时,不要弄乱缩进。选择您的代码,然后使用编辑框顶部的{}
按钮对其进行格式化。它会为你做一切。