在Python中,我正在编写一个类,其中一些属性必须在对象的生命周期内保持不变。
一种方法是使用属性(properties):
一种方法是使用属性(properties):
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()
这是否被视为一种良好的实践?我是否应该仅依赖文档来展示哪些属性是可写的,哪些不是?还有其他建议吗?
Foo.x
时已经引发了 AttributeError 异常,当存在一个没有 setter 的属性时,这是默认行为。因此,我认为添加 setter 是没有用的。 - ndou