mar*_*t1n 3 python properties class
我有以下使用两个简单属性的代码:
class Text(object):
@property
def color(self):
return 'blue'
@property
def length(self):
return 22
t = Text()
print t.color
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它显然返回blue. 但是我怎样才能在代码中动态更新颜色的值呢?即当我尝试做:
t = Text()
print t.color
t.color = 'red'
print t.color
Run Code Online (Sandbox Code Playgroud)
它失败并出现can't set attribute错误。有没有办法修改属性的值?
编辑:
如果上面的代码被重写为在 williamtroup 的回答中使用 setter,那么简单地将其缩短为:
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
Run Code Online (Sandbox Code Playgroud)
您需要一个属性设置器和一个类变量来存储数据。
以你的例子:
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
Run Code Online (Sandbox Code Playgroud)