0
我使用的是類裝飾,但我不明白與SETATTR如何設置屬性,這是我的代碼:__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]
也許解釋你認爲這應該達到什麼? – Marcin 2012-02-23 14:40:33
* * par在你的代碼中做了什麼?您將其保留未使用... – glglgl 2012-02-23 14:43:50
您發佈的代碼不會生成您顯示的輸出。我得到的輸出是''[3,4,9] \ n X is => [1,2,3]'' – AdamKG 2012-02-23 14:46:50