define
Alex Martelli
aleax at aleax.it
Tue May 13 04:05:51 EDT 2003
<posted & mailed>
Turhan Ozen wrote:
> __getattr__ is getting into infinite loop. I just copied the code. Could
> you please help me how to avoid this?
Sure -- there were a couple of booboos (which is why I warned that the
code was untested;-), easy to fix -- so, here's a working script:
class list_with_names(list):
__names = {}
def __init__(self, names):
list.__init__(self, len(names)*[None])
self.__names = {}
for i, name in enumerate(names):
self.__names[name] = i
def __getattr__(self, name):
try: return self[self.__names[name]]
except KeyError: raise AttributeError
def __setattr__(self, name, value):
try: self[self.__names[name]] = value
except LookupError: object.__setattr__(self, name, value)
if __name__ == '__main__':
# minimal self-test only if run as main script
# e.g. a list of 5 items
x = list_with_names(
'aname another yetanother onemore andthistoo'.split())
x[1] = 23
print x.another
print x
This prints:
23
[None, 23, None, None, None]
Alex
More information about the Python-list
mailing list