Returning a list/dict as "read-only" from a method ?
Sean Ross
sross at connectmail.carleton.ca
Thu Dec 26 11:15:19 EST 2002
The following is a possible solution. However, it does not return a
list/dict as read-only from a method.
Rather, it wraps your list/dict in a read-only property.
Also, I only deal with data as a dictionary, not as a list. But, it's the
same idea.
class C:
def __init__(self):
# here we're just dealing with self.__data as a dict
self.__data = { "hello": "world", "how":"are", "you":"today"}
def get_data(self):
return lambda key: self.__data[key]
def get_keys(self):
return self.__data.keys()
# if self.__data is a list, return range(len(self.__data))
data = property(get_data)
keys = property(get_keys)
if __name__ == "__main__":
inst = C()
for key in inst.keys:
print "inst.data[%s]: %s " % (key, inst.data(key))
Hope this helps,
Sean
More information about the Python-list
mailing list