calling objects parents' __init__?

Peter Hansen peter at engcorp.com
Mon Sep 15 16:35:41 EDT 2003


user at domain.invalid wrote:
> 
> Normally, when I inherit from a class that I have written,
> I want instances of the new class to call the __init__ of
> the old (actually, starting from the top of the tree, and
> moving on down).
> 
> What is the preferred way to do this?

The preferred way is to call your parent's __init__, if it
has one:

class Parent:
    def __init__(self):
        # useful stuff happens here

class Child:
    def __init__(self):
        Parent.__init__(self)
        # other stuff, some useful, happens here

There are more sophisticated, less readable approaches, and I suspect
Python 2.2 or 2.3 add a new idiom as well.

-Peter




More information about the Python-list mailing list