问题描述
为防止覆盖类变量,通常的做法是“隐藏”底层存储self._data
后面的数据,并公开@property
方法以返回数据。但是,这不适用于列表:您无法覆盖整个对象(好的),但是[:]
访问条目,而@property
保护无效。
class Test:
def __init__(self):
self._data = [0,1,2]
@property
def data(self):
return self._data
obj = test()
print(obj.data)
# obj.data = [99] # `AttributeError: can't set attribute` -- Good.
obj.data[:] = [99] # Yikes!
print(obj.data)
[0,2]
[99]
有什么主意如何防止覆盖?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)