Question: Inheritance from a buil-in type

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Sep 29 10:51:32 EDT 2003


"T. Kaufmann" <merman at snafu.de> wrote in news:3F7848C6.8070306 at snafu.de:

> A simple but important question:
> 
> How can I initialize a super class (like dict) correctly in my
> subclass constructor? 
> 
> A sample:
> 
> class MyClass(dict):
>      def __init__(self):
>          dict.__init__(self)
>          ...
> 
> 
> Is there a general rule to do this for all buil-in types?

There are two rules. Generally, immutable objects get their initial values 
from the constructor (__new__) while mutable objects are constructed with a 
default value (e.g. empty list or dict) and are then set by the initialiser 
(__init__) method. A few types which you might expect to be immutable are 
actually mutable (e.g. property).

Mutable example (use for list, dict, property, etc.):

    class MyClass(dict):
        def __init__(self, *args, **kw):
            dict.__init__(self, *args, **kw)

Immutable example (use for tuple, int, etc.):

    class MyClass(tuple):
        def __new__(cls, *args, **kw):
            return tuple.__new__(cls, *args, **kw)

If there is any chance of your class being subclassed with multiple 
inheritance involved, you should consider using super instead of naming the 
baseclass directly, but most of the time you can get away with a direct 
call to the baseclass.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list