Newbie Question: Giving names to Elements of List/Tuple/Dict
holger krekel
pyth at devel.trillke.net
Sat Nov 30 10:50:46 EST 2002
Oren Tirosh wrote:
> On Sat, Nov 30, 2002 at 02:41:02PM +0100, holger krekel wrote:
> > > class record(dict):
> > > def __init__(self, initfrom=(), **kw):
> > > dict.__init__(self, initfrom)
> >
> > But this pollutes the instance's namespace.
>
> Do you mean that dict methods without double-underscores? Yes, of you
> add a field called 'keys' to a record it will override the 'keys'
> method inherited from dict.
that's what i meant, yes.
> > Is inheriting from the dict class really neccessary?
>
> Another way to achieve this effect is overloading __getattr__, __setattr__
> but it requires more code and is *much* slower.
just
class record(object):
def __init__(self, initfrom=(), **kw):
self.__dict__ = dict(initfrom)
self.__dict__.update(kw)
is *not* slower.
But it doesn't offer item-access (__get/set/delitem__)
which is handy for non-string keys. There you can use getattr/setattr/
hasattr/delattr on a record instance. If you really want to have the
dictish methods then you could do
self.__getitem__ = self.__dict__.__getitem__
self.__setitem__ = self.__dict__.__setitem__
self.__delitem__ = self.__dict__.__delitem__
etc. in the __init__ constructor. But I consider the dictish usage
to be exceptional because otherwise you would use a dict anyway :-)
And for common (usual record/struct) usage
r['name']
is more noisy and less convenient than
r.name
cheers,
holger
More information about the Python-list
mailing list