UserDict question

Alex Martelli aleax at aleax.it
Tue Nov 4 15:39:28 CET 2003


Guyon Morée wrote:

> Hi all,
> 
> I am using the UserDict baseclass and I want to add a __init__ to it to
> set up some initial values.
> 
> my question is: do I have to run UserDict.UserDict.__init__ before doing
> anything else?

The normal way to proceed is indeed to call your base class's __init__
before proceeding, yes.

> as in:
> 
> class myClass(UserDict.UserDict):
>   def __init__(self):
>     UserDict.UserDict.__init__ (self)
>     self.value = 1

If you don't want to support myClass being called with arguments
in order to initialize its instances to non-empty dictionaries,
this may indeed be sufficient.


> it seems so easy, but somehow i don't really grasp it... what do i have to
> do?

If you also want to support optional arguments, you'll code something like:

class myClass(UserDict.UserDict):
    def __init__(self, adict=None, **kwargs):
        UserDict.UserDict.__init__ (self, adict, **kwargs)
        self.value = 1

in order to accept such optional args and pass them on to UserDict
for initialization.  But, if you want to myClass to be always
called without arguments (all its instances start out empty) then
the code you wrote above is indeed correct.


Alex





More information about the Python-list mailing list