Question: Inheritance from a buil-in type

Alex Martelli aleax at aleax.it
Mon Sep 29 17:36:47 CEST 2003


T. Kaufmann wrote:

> Hi there,
> 
> A simple but important question:
> 
> How can I initialize a super class (like dict) correctly in my subclass
> constructor?

Generally, you also want to override __new__ -- not in all cases can 
you do all you want in __init__ by itself (e.g., it's far too late 
when you inherit from immutable types, such as numbers, str, tuple).


> A sample:
> 
> class MyClass(dict):
>      def __init__(self):
>          dict.__init__(self)
>          ...

Yeah, you can do this, but the dict.__init__ call with just the
self parameter is actually redundant (it wouldn't be if there
WERE arguments -- either keyword ones, or a sequence of pairs,
or both -- with which to actually initialize a non-empty dict...).


> Is there a general rule to do this for all buil-in types?

Generally, the super built-in may be advisable if you think you
may ever be involved in a multiple-inheritance graph.  But that
is no different whether built-in types are involved, or not.  I'm
not sure what "general rule" may be different for built-in types
than for others -- offhand, I don't think there are such differences.


Alex





More information about the Python-list mailing list