I'm using a class decorator but I didn't understand how set attribute with setattr, this is my code:
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))
but when i do:
if __name__ == "__main__":
X = Doubler('X is ', [1,2,3])
X.xxx = [3,4,9]
print(X.xxx)
X.display()
i have this output:
[3, 4, 9]
X is => [1, 2, 3]
how can i do for having this output?
[3, 4, 9]
X is => [3, 4, 9]
Your display
method only prints the data in self.data
, but you've created an attribute caled xxx
. Of course display
doesn't display it. This works:
>>> X.data = [3,4,9]
>>> X.display()
X is => [3, 4, 9]