如果您不想复制数据,并且想要传递不可更改的“列表”,一种方法是创建一个代理对象,列表的副本,这会禁用所有更改方法,并引用读取方法到原始列表 - 一些内容:
from collections import UserList
class ReadOnlyList(UserList):
def __init__(self, original):
self.data = original
def insert(self, index=None, value=None):
raise TypeError()
__setitem__ = insert
__delitem__ = insert
append = insert
extend = insert
pop = insert
reverse = insert
sort = insert
通过子类化“UserList”,可以确保处理列表数据的所有代码都将通过公开公开的 Python 方法,更好的是,所有其余方法都已实现并代理到内部data
属性。
下面是 2014 年的原始答案,重点关注 Python 2
class ReadOnlyList(list):
def __init__(self, other):
self._list = other
def __getitem__(self, index):
return self._list[index]
def __iter__(self):
return iter(self._list)
def __slice__(self, *args, **kw):
return self._list.__slice__(*args, **kw)
def __repr__(self):
return repr(self._list)
def __len__(self):
return len(self._list)
def NotImplemented(self, *args, **kw):
raise ValueError("Read Only list proxy")
append = pop = __setitem__ = __setslice__ = __delitem__ = NotImplemented
And, of course, implement whatever other methods you judge necessary, either raising the error (or ignoring the writting instruction) - or acessing the corresponding object in the internal list.