Reputation: 6213
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
Upvotes: 6
Views: 18723
Reputation: 13131
You need a setter for the property and a class variable to store the data.
With your example:
class Text(object):
def __init__(self):
self._color = "blue"
self._length = 12
@property
def color(self):
return self._color
@color.setter
def color(self, value):
self._color = value
@property
def length(self):
return self._length
@length.setter
def length(self, value):
self._length = value
Upvotes: 8