automatic accessors to a member var dict elements?

Jeff Shannon jeff at ccvcorp.com
Fri Oct 15 15:36:43 EDT 2004


Jeff Shannon wrote:

> Nick Craig-Wood wrote:
>
>> 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...)


And, because I'm slacking off on my real work:

 >>> class MyClass(object):
...     def __init__(self):
...         self.__dict__['m_dict'] = {'one':1, 'two':2, 'three':3}
...     def __getattr__(self, attr):
...         try:
...             value = self.m_dict[attr]
...         except KeyError:
...             raise AttributeError(attr)
...         return value
...     def __setattr__(self, attr, value):
...         self.m_dict[attr] = value
...        
 >>>
 >>> obj = MyClass()
 >>> obj.one
1
 >>> obj.two
2
 >>> obj.one = 'won'
 >>> obj.one
'won'
 >>> obj.four = 4
 >>> obj.m_dict
{'four': 4, 'three': 3, 'two': 2, 'one': 'won'}
 >>> obj.five
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 8, in __getattr__
AttributeError: five
 >>>

Hm, that error message is a bit weak.  If we replace the 'raise 
AttributeError(attr)' with '''raise AttributeError("%s instance has no 
attribute '%s'" % (self.__class__.__name__, attr))''', we'll get an 
error message that's much more in line with a 'normal' AttributeError.

 >>> obj.five
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 8, in __getattr__
AttributeError: MyClass instance has no attribute 'five'
 >>>

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list