OUTDATED, DO NOT USE: This tutorial was written in 1999 and was based on Python 1.5.2, which today is a really old version. I would not recommend using this tutorial to learn modern Python as the language has changed significantly. This page is left here in it's mostly-original form for historic reference only. Please consult the Python website for current documentation.

Inheritance

  • You can derive one class from another. Derived classes inherit all the attributes of the parent class, including all member functions and variables.
    class superclass:
       def compute( self, a, b ):
          return a + b
    
    class subclass( superclass ):
       pass # add nothing extra
    
    x = subclass()
    x.compute( 3, 4 )   --> 7
    
  • Derived classes may add additional attributes or override definitions from the parent
    class publication:
       def set_creator( self, name ):
          self.creator = name
    
    class book( publication ):
       def set_creator( self, author, publisher ):
          self.creator = ( author, publisher )
       def set_isbn( self, booknumber ):
          self.isbn = booknumber
    
  • Unlike C++, when a subclass overrides a member function of the parent, the parent's function is never called--even for constructors. If you want to parent's constructor to be called, you must call it directly.
    class myfile:
       def __init__( self, filename ):
          self.file = open( filename, "w" )
       def write( self, text ):
          self.file.write( text )
    
    class mytempfile( myfile ):
       def __init__( self ):
          myfile.__init__( self, "tempfilename.txt" )
    
    

Multiple inheritance

  • To derive from more than one class, just list all the parent classes in the definition,
    class textcontents:
       defintion for book contents
    
    class coverart:
       definition for coverart
    
    class book( textcontents, coverart ):
       def print( self ):
          self.coverart.print( self )
          self.textcontents.print( self )
    
  • When an attribute is defined by more than one parent and not by the child, the order in which the parents are listed is used to figure out which one to use. The first parent to define the attribute is used.
    class textcontents:
       def author(self): ...
    
    class coverart:
       def author(self): ...
    
    class book( textcontents, coverart ):
       ...
    
    a = book()
    a.author()   # Refers to author() method of textcontents class