【发布时间】:2015-08-17 14:51:23
【问题描述】:
在 Python 中,我正在编写一个类,其中某些属性在对象生命周期内必须保持不变。
一种方法是使用属性:
class Foo:
def __init__(self, x, y):
'''Create a Foo object
x -- list of int (READ-ONLY)
y -- float
'''
# Save x and y and ensure they are int
self._x = [int(xx) for xx in x]
self.y = float(y)
@property
def x(self):
# Return a copy of self._x to prevent accidental modification
return self._x.copy()
这被认为是一种好的做法吗?我应该只依靠文档来展示哪些属性是可写的,哪些是不可写的?还有什么建议吗?
【问题讨论】:
标签: python properties attributes private readonly