Newbie Question: Giving names to Elements of List/Tuple/Dict

Oren Tirosh oren-py-l at hishome.net
Sat Nov 30 07:45:47 EST 2002


On Fri, Nov 29, 2002 at 04:01:15PM +0100, holger krekel wrote:
> Additionally using
> 
>     class Struct:
>         def __init__(self, **kw):
>             self.__dict__.update(kw)
> 
> is also a nice idiom. You can then say
> 
> >>> one = Struct(name='guido', phone='5555')
> >>> one.name
> 'guido'
> >>> one.phone
> '5555'

If you want something even fancier, try this:

class record(dict):
    def __init__(self, initfrom=(), **kw):
        dict.__init__(self, initfrom)
        self.update(kw)
        self.__dict__ = self

    def __repr__(self):
        return "%s(%s)" % (self.__class__.__name__,
          ', '.join(['%s=%s' % (k, repr(v)) for k,v in self.items()]))

You can access fields as either attributes or dictionary items. Even
tab completion works. The repr of this object is the constructor call 
to re-create it.

        Oren





More information about the Python-list mailing list