automatic accessors to a member var dict elements?

Nick Craig-Wood nick at craig-wood.com
Fri Oct 15 01:46:35 EDT 2004


Christopher J. Bottaro <cjbottaro at alumni.cs.utexas.edu> wrote:
>  If I have the following class:
> 
>  class MyClass:
>          def __init__(self):
>                  m_dict = {}
>                  m_dict['one'] = 1
>                  m_dict['two'] = 2
>                  m_dict['three'] = 3
> 
>  Is there anyway to generate automatic accessors to the elements of the dict? 
>  For example, so I could say:
> 
>  obj = MyClass()
>  obj.one # returns obj.my_dict['one']
>  obj.one = 'won' # same as obj.my_dict['one'] = 'won'
> 
>  By automatic, I mean so I don't have to write out each method by hand and
>  also dynamic, meaning if m_dict changes during runtime, the accessors are
>  automatically updated to reflect the change.

Here is an old style class way of doing it.  I think there might be a
better way with new style classes but I'm not up to speed on them!

Note care taken to set m_dict as self.__dict__["m_dict"] rather than
self.m_dict otherwise the __setattr__ will recurse!  You can put a
special case in __setattr__ if you prefer.

class MyClass:
    def __init__(self):
        self.__dict__["m_dict"] = {}
        self.m_dict['one'] = 1
        self.m_dict['two'] = 2
        self.m_dict['three'] = 3
    def __getattr__(self, name):
        return self.m_dict[name]
    def __setattr__(self, name, value):
        self.m_dict[name] = value

>>> obj = MyClass()
>>> print obj.one
1
>>> obj.one = 'won'
>>> print obj.one
won

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



More information about the Python-list mailing list