automatic accessors to a member var dict elements?

Alex Martelli aleaxit at yahoo.com
Mon Oct 18 17:55:54 CEST 2004


Michael Loritsch <loritsch at gmail.com> wrote:
   ...
> 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?

Any deliberate seeding of confusion between items and attributes will
eventually cause grief, IMHO.  Specifically, I'd find it unnerving that
after foo=MyClass(), some foo[x]=y for runtime read/computed values of x
and y may make all kinds of methods unaccessible on foo -- say
foo.keys(), foo.pop(), and so on.  Basically, any such foo would need to
be only ever accessed by implied lookup of special methods (working on
the class, and not the instance, fortunately), and never by any name
lookup of a method on the instance itself.  Looks like a deliberate
attempt to put oneself in a fragile, error-prone situation.  Maybe I'm
just a pessimist!


Alex



More information about the Python-list mailing list