Python - Class Extension Techniques


Extension is only one way to interface with a superclass.

The following table lists a variety of common techniques:

Techniques Description
Super Defines a method function and a delegate that expects an action in a subclass.
Inheritor Doesn't provide any new names, so it gets everything defined in Super.
Replacer Overrides Super's method with a version of its own.
ExtenderCustomizes Super's method by overriding and calling back to run the default.
Provider Implements the action method expected by Super's delegate method.


class Super: 
   def method(self): 
       print('in Super.method')           # Default behavior 
   def delegate(self): 
       self.action()                      # Expected to be defined 
# from   w w  w.j  a va 2  s.c om
class Inheritor(Super):                    # Inherit method verbatim 

class Replacer(Super):                     # Replace method completely 
   def method(self): 
       print('in Replacer.method') 

class Extender(Super):                     # Extend method behavior 
   def method(self): 
       print('starting Extender.method') 
       print('ending Extender.method') 

class Provider(Super):                     # Fill in a required method 
   def action(self): 
       print('in Provider.action') 

if __name__ == '__main__': 
   for klass in (Inheritor, Replacer, Extender): 
       print('\n' + klass.__name__ + '...') 
   x = Provider() 


Related Topic