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 Implementation of a Method

Credit: Alex Martelli

Problem

You need functionality equivalent to Java’s super keyword to delegate part of a method to a superclass.

Solution

When you override the method of a superclass, you often want to call the superclass’s version of a method as part of your override. In a Python 2.2 new-style class, the new built-in super function helps a lot:

class A(B, C):
    def amethod(self):
        # First, call the superclass's version
        super(A, self).amethod(  )
        # Continue with A-specific implementation
        ...

With super, you transparently call amethod in the B or C superclass, or in both, if both classes define it, and B also uses super in the same way.

This doesn’t work for classic classes (or in Python 2.1 and earlier), but we can arrange for a slightly weaker version:

def super(class_, inst): # First, try the real thing, if available and applicable try: return _ _builtins_ _.super(class_, inst) except (TypeError, AttributeError): pass # Otherwise, arrange for a weaker substitute class Super: def _ _init_ _(self, class_, inst): # Just remember the bases and instance self.bases = class_._ _bases_ _ self.inst = inst def _ _getattr_ _(self, name): # Seek the bases for an unbound method; break when found for base in self.bases: method = getattr(name, method, None) if method is not None: break else: raise AttributeError, name # No base has it, so raise # Found, so create and return the bound-method version import new return new.instancemethod(method, self.inst, ...
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