A brief introduction to object-oriented programming in Python: Part 2, inheritance

September 2, 2005


A while ago I posted a tiny introduction to object-oriented programming in Python. Here's part two, about inheritance. It's equally tiny and equally doesn't attempt to be comprehensive.


Inheritance is a way of specifying a new class that's almost, but not exactly, like a class you already have. Let's extend the example from the page above. Assume that I (or maybe someone who has written a library module) has already defined class c3 for us:


>>> class c3:

...   def __init__(self,x):

...     self.val=x

...   def getValAsDouble(self):

...     return self.val*2


And let's assume that, for the purposes of the program we're writing, that's a useful class. But it would be even more useful if it had a getValAsTriple() method. I can save some work by saying that class c4 inherits from class c3. Then I only need to specify what I want to add:


>>> class c4(c3):

...   def getValAsTriple(self):

...     return self.val*3

...

>>> o6=c4(42)

>>> o6.getValAsDouble() # Comes for free through inheritance from c3

84

>>> o6.getValAsTriple() # Defined in c4

126


As a matter of terminology, the class you inherit from is often called the "superclass" and your class that inherits from it is its "subclass".


Now, it's pretty rare that you find a class that just happens to be useful to inherit from. Many classes that you inherit from were designed specifically to be inherited from.


Inheritance has another advantage: If the class you inherit from is supplied by a library module, you don't have to know or care about the details of how it gets its work done.


Let's say that the author of some module thinks of a better way for one of its classes to do something. Or maybe they fix a bug or two. If you install the new version of the library, you get the improvements "for free". You don't have to go to any extra trouble, because you're now inheriting from the improved version.


There's one more thing: What does inheriting from "object" do? That class is more like a signal than a class that provides useful methods that you'll use every day. It tells Python that you want your class to be a "new-style" class. New-style classes solve a few problems that not very many people have. (For those people they're important, but nobody who's starting out with object-oriented programming is one of them.) So don't worry about inheriting from object any time soon. I've been programming in Python for years and very rarely need to use a new-style class.