我正在使用类装饰器,但我不明白如何使用 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]
答案 0 :(得分:2)
您的display
方法仅打印self.data
中的数据,但您创建了一个名为xxx
的属性。当然display
不会显示它。这有效:
>>> X.data = [3,4,9]
>>> X.display()
X is => [3, 4, 9]