automatic accessors to a member var dict elements?
Jeff Shannon
jeff at ccvcorp.com
Fri Oct 15 14:20:59 EDT 2004
Nick Craig-Wood wrote:
>>>>class MyClass(object): # ensure a new-style class
>>>>
>>>>
>... def __init__(self):
>... self.m_dict = {'one':1, 'two':2, 'three':3}
>... def __getattr__(self, attr):
>... value = self.m_dict.get(attr, None)
>... if value is None:
>... raise AttributeError(attr)
>... return value
>... def __setattr__(self, attr, value):
>... self.m_dict[attr] = value
>...
>
>
>>>>obj = MyClass()
>>>>
>>>>
>Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 3, in __init__
> File "<stdin>", line 10, in __setattr__
> File "<stdin>", line 5, in __getattr__
> File "<stdin>", line 5, in __getattr__
> File "<stdin>", line 5, in __getattr__
> File "<stdin>", line 5, in __getattr__
> File "<stdin>", line 5, in __getattr__
>[snip]
> File "<stdin>", line 5, in __getattr__
> File "<stdin>", line 5, in __getattr__
>RuntimeError: maximum recursion depth exceeded
>
>I know there is something different about new style classes in this
>area, but thats not it!
>
>
Hmmm... Actually, I think that the problem here is that during
__init__(), we're trying to set the attribute m_dict, which doesn't
exist yet, so it tries to look in self.m_dict to find it...
Modifying __init__() so to use self.__dict__['m_dict'] instead of
self.m_dict will likely fix this. (But I still haven't tested it...)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list