automatic accessors to a member var dict elements?

Nick Craig-Wood nick at craig-wood.com
Fri Oct 15 04:30:02 EDT 2004


Jeff Shannon <jeff at ccvcorp.com> 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
> 
>  I'm using a new-style class to take advantage of improvements in 
>  attribute lookup.  For this class, __getattr__()/__setattr__() will only 
>  be called if attr isn't found through the normal attribute resolution 
>  rules. 

It doesn't!

>>> 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!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list