pre-PEP generic objects

Steven Bethard steven.bethard at gmail.com
Tue Nov 30 16:03:36 EST 2004


Scott David Daniels wrote:
> Nick Craig-Wood wrote:
> 
>> class Hash:
>>     def __init__(self, **kwargs):
>>         for key,value in kwargs.items():
>>             setattr(self, key, value)
>>     def __getitem__(self, x):
>>         return getattr(self, x)
>>     def __setitem__(self, x, y):
>>         setattr(self, x, y)
> 
> 
> You can simplify this:
> class Hash(object):
>     def __init__(self, **kwargs):
>         for key,value in kwargs.items():
>             setattr(self, key, value)
>     __getitem__ = getattr
>     __setitem__ = setattr

Oh, I guess I should mention that Hash actually does something Bunch is 
not intended to -- it supports __getitem__ style access in addition to 
dotted-attribute (__getattr__) style access.  Bunch is intended only to 
support dotted-attribute style access, though it does support the 
one-way conversion of a mapping object to a Bunch.

Steve



More information about the Python-list mailing list