automatic accessors to a member var dict elements?

Michael Loritsch loritsch at gmail.com
Sat Oct 16 13:34:53 EDT 2004


Nick Craig-Wood <nick at craig-wood.com> wrote in message news:<slrncmtp34.lr2.nick at irishsea.home.craig-wood.com>...
> 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

To me, it appears the Christopher is simply looking for a way to
get/set members of a dictionary using a different syntax.

That being the case, why not create a pythonic solution like the one
above using new style classes, as we can derive directly from the dict
type?

In this case, we will just forward the __getattr__ and __setattr__
calls to __getitem__ and __setitem__, respectively.

Here is the equivalent solution:

class MyClass (dict):             #New style class derived from dict
type

    #Use same get/set syntax desired during construction
    def __init__(self): 
        self.one = 1              
        self.two = 2
        self.three = 3

    #Get/set syntax changed with simple forwarding functions
    def __getattr__(self, key):
        return self.__getitem__(key)
    def __setattr__(self, key, value):
        self.__setitem__(key, value)


Isn't this the type of thing that Guido van Rossum envisioned in
trying to unify types and classes?

Michael Loritsch



More information about the Python-list mailing list