【发布时间】:2016-07-01 23:04:52
【问题描述】:
我有以下使用两个简单属性的代码:
class Text(object):
@property
def color(self):
return 'blue'
@property
def length(self):
return 22
t = Text()
print t.color
当我运行它时,它显然返回blue。但是如何在代码的后面动态更新颜色的值呢? IE。当我尝试这样做时:
t = Text()
print t.color
t.color = 'red'
print t.color
失败并出现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
【问题讨论】:
-
回答您的编辑;不是 Pythonic 和坏习惯。
-
@EddB 怎么不是 Pythonic?
-
不管怎样,问题都得到了回答。由您决定哪种方法是实现您的课程的最佳方式。
-
阅读this
标签: python class properties