26: Inheritance

In Object Oriented Programming(OOP), a great benefit is to reuse code. Inheritance is one way to achieve this.

Inheritance enables us to make new class based on an existing class. The new class(child class or subclass) will inherit all the attributes of the existing class(parent class or superclass), and you can use those attributes as if they were defined in the child class. On top of that, a child class can also override attributes from the parent class or have extra features of its own.

Parent and Child Classes

Syntax

Child class is declared as usual class, only after it's name, a parentheses enclose the Parent class name:

class Parent:
    code...

class Child(Parent):
    code...

FarmAnimal & Duck

Let's see an example of a parent class FarmAnimal, a child class Duck to show how inheritance works:

class FarmAnimal:
    def __init__(self, type, legNumber):
        self.type = type
        self.legNumber = legNumber

    def where(self):
        print("%s lives on the farm." % (self.type))      

    def describe(self):
       print( "%s has %d legs." %(self.type, self.legNumber) )



class Duck(FarmAnimal):
    def makeSound(self):
        print("Quark! Quark! Quark!")

In class FarmAnimal, we defined a __init__() (two instance variables type and legNumber ); method, where() shows the place a farm animal lives; method describe() shows information about the object.

Instead of starting from scratch, another class Duck is derived from a preexisting class FarmAnimal by putting the parent class name in parentheses after the new class name ( Duck(FarmAnimal) ) in the header line.

Duck is a child class of FarmAnimal, it will inherent all the attributes of it's parent class FarmAnimal. Duck uses the parent __init__() for initialization. Let's see:

(Continue)

# create a Duck instance
duck = Duck('Duck', 2)      
print( duck.legNumber )     # 2 (variable defined in parent class)

duck.describe()       # Duck has 2 legs. (method from parent class)

duck.where()           # Duck lives on the farm.

duck.makeSound()      # Quark! Quark! Quark! (method of it's own)

From the above example of parent, child classes, we can see that the child class Duck inherit all the attributes defined in the parent class, it has __init__(), describe() and where() methods from the parent class; it also has it's own method makeSound().

results matching ""

    No results matching ""