1

我正在使用类装饰器,但我不明白如何使用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] 
4

1 回答 1

2

您的display方法仅打印 中的数据self.data,但您创建了一个属性 caled xxx。当然display不会显示。这有效:

>>> X.data = [3,4,9]
>>> X.display()
X is  => [3, 4, 9]
于 2012-02-23T14:55:20.150 回答