July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Alex Martelli
You need
functionality equivalent to Java’s
super keyword to delegate part
of a method to a superclass.
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, ...