I have the following code that uses two simple properties:
class Text(object):
@property
def color(self):
return 'blue'
@property
def length(self):
return 22
t = Text()
print t.color
When I run this, it obviously returns blue
. But how can I update the value of color on the fly later in the code? I.e. when I try to do:
t = Text()
print t.color
t.color = 'red'
print t.color
It fails with a can't set attribute
error. Is there a way to modify the value of a property?
EDIT:
If the above code is rewritten to use setters as in williamtroup's answer, what is the advantage of simply shortening it to:
class Text(object):
def __init__(self):
self.color = self.add_color()
self.length = self.add_length()
def add_color(self):
return 'blue'
def add_length(self):
return 22