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 followsFor 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 followsDiscussion
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)