====== Python Inheritance Fundamentals ====== Any language that supports object orientation will let you create objects, either by instantiating them from classes or by building them from prototypes. Class-based object orientation becomes significantly more powerful when you are able to use **inheritance**. ===== What you'll need to know ===== * How to create and use a Python class. * How to use the ''@property'' decorator. * How to use parameterized constructors. ===== What you'll learn ===== * Inheritance core concept * Generalization and specialization * Class heirarchies * Inheritance and code reuse * Inheritance in Python ===== Inheritance ===== In the real world, we often create hierarchies of things. For example, a //vehicle// is "a machine that is used to carry people or goods from one place to another".(("Merriam-Webster's Learner's Dictionary." Merriam-Webster's Learner's Dictionary. [[http://www.learnersdictionary.com/search/vehicle]] (accessed February 10, 2011).)) Based on this general concept, we may define a category of //two-wheel// vehicles that includes //bicycles// and //motorcycles//, a category called //car// that includes //sedans//, //coupes//, and //convertibles//, a //truck// category that includes //buses//, //vans//, //tractors//, and so on. {{vehicle.png?750|vehicle heirarchy}} In these kinds of hierarchies, we typically start with a general class of things at the root of the tree, and all the other classes of things are more specialized versions of the general class of things. This is the essence of inheritance in object oriented programming. For example, to solve a particular programming problem, we might define a ''Person'' class, and based on that definition we might then define an ''Employee'' class, and then based on that ''Employee'' class we might define ''Manager'', ''Staff'', and ''Hourly'' employee classes. {{employee.png|employee heirarchy}} Or, we might define a general ''Shape'' class. Then based on the ''Shape'' class we might define ''Rectangle'' and ''Ellipse'' classes. Then based on the ''Rectangle'' class we might define a ''Square'' class (a square is rectangle with equal height and width), and based on the ''Ellipse'' class we might define a ''Circle'' (a circle is an ellipse with zero eccentricity). {{shape.png|shape heirarchy}} ==== Generalization and specialization ==== In both of the above cases, the classes closest to the root of the tree are more general than the classes toward the bottom. A ''Square'' is a special kind of ''Rectangle'' and a ''Rectangle'' is a special kind of ''Shape''. An ''Hourly'' employee is a special kind of ''Employee'', and an ''Employee'' is a special kind or ''Person''. For this reason, we often say that inheritance defines //"is a"// relationships. ==== Class heirarchies ==== We call trees of classes like the above **class heirarchies**. The class at the root of the tree is a **base class**, and classes that inherit from a base classes are **derived classes**.((Synonyms for **base class** are **superclass** and **parent class**. Synonyms for **derived class** are **subclass** and **child class**. You should generally stick to one pair---(base class:derived class), (superclass:subclass), or (parent class:child class).)) ==== Inheritance and code reuse ==== One of the advantages of implementing classes with inheritance is **code reuse**. Almost all class-based object oriented languages let you define derived classes //without having to re-write the base class code//. The idea is that you write the base class code //once//. Then when you write the derived classes, you add only whatever new code is required for the derived class or new definitions for old code that must be **overridden**. Since you do not need to rewrite the code that is common to both base and derived classes, you end up writing less code. But even more important, when you fix a bug in the base class, it automatically propagates to the derived classes. ===== Inheritance in Python ===== To demonstrate the use of inheritance in Python, we are going to create a specialized version of one of these:((Picture from: "Totty Clicker - Gadgets at Play.com (UK)." Play.com (UK): DVDs, Music CDs, MP3s, Video Games, Books, Electronics & Gadgets - Free Delivery. [[http://www.play.com/Gadgets/Gadgets/4-/11566684/Totty-Clicker/Product.html?ptsl=1&ob=Price&fb=0#]] (accessed January 25, 2011). )) \\ {{tottycounter.jpg?234|}} A standard ''ClickerCounter'' has two buttons: one for incrementing the count and another for resetting it. We are going to use inheritance to create a special kind of ''ClickerCounter'': one that has an additional button to decrement the counter. In terms of a Python model, a ''ClickUpDown'' is identical to a ''ClickerCounter'' except that it has an additional method: ''click_down''. {{:python:about_python:clickupdown-tree.png}} Here is the base class: # base class definition class ClickerCounter(): def __init__(self): self.count = 0 # accessor for count def get_count(self): return self.count # click the counter def click(self): self.count = self.count + 1 # reset the count def reset(self): self.count = 0 And here is the derived class: # derived class definition class ClickUpDown(ClickerCounter): # click down the counter def clickdown(self): self.count = self.count - 1 That's it! Using the new class: b = ClickUpDown() # instantiate a ClickUpDown object b.click() # 1 b.click() # 2 b.click() # 3 b.clickdown() # should be 2 print b.get_count() a = ClickerCounter() # instantiate a ClickerCounter object a.click() # 1 a.click() # 2 a.click() # 3 a.clickdown() # can't do that! print a.get_count() ===== What you should do next ===== This covers the very basics of inheritance in Python. To level up your use of inheritance in Python, you should next have a look at the following: * Overriding methods. * Derived class constructors (including calling parent class constructors). Copyright © 2011-2018 Mithat Konar. All rights reserved.