Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Calling a Superclass _ _init_ _ Method if It Exists

Credit: Alex Martelli

Problem

You want to ensure that _ _init_ _ is called for all superclasses that define it, and Python does not do this automatically.

Solution

There are several ways to perform this task. In a Python 2.2 new-style class, the built-in super function makes it easy (as long as all superclass _ _init_ _ methods also use super similarly):

class NewStyleOnly(A, B, C):
    def _ _init_ _(self):
        super(NewStyleOnly, self)._ _init_ _(  )
        # Subclass-specific initialization follows

For classic classes, we need an explicit loop over the superclasses, but we can still choose different ways to handle the possibility that each superclass may or may not have an _ _init_ _ method. The most intuitive approach is to “Look Before You Leap” (LBYL), i.e., check for existence before calling. While in many other cases LBYL has problems, in this specific case it doesn’t, so we use it because it is the simplest approach:

class LookBeforeYouLeap(X, Y, Z):
    def _ _init_ _(self):
        for base in self._ _class_ _._ _bases_ _:
            if hasattr(base, '_ _init_ _'):
                base._ _init_ _(self)
        # Subclass-specific initialization follows

Discussion

Often, we want to call a method on an instance (or class) if and only if that method exists. Otherwise, we do nothing or default to another action. For example, this often applies to the _ _init_ _ method of superclasses, since Python does not automatically call this method if it exists. A direct call of X._ _init_ _(self)

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata