How to create a class by inheriting another class

What is inheritance

We can create a class by inheriting all features from another class. For example, we can create a class called Rectangle by inheriting a class called Shape. Suppose Shape class already has properties we need for Rectangle.

In the following we define a class called A first and A has a method called hello. When creating class B we inherit A by placing A in parentheses.


class A: # from   ww w.j  a  v  a2  s . c  om
    def hello(self): 
        print "Hello, I'm A." 

class B(A): 
    pass 

a = A() 
b = B() 
a.hello() 
b.hello() 

The code above generates the following result.

The class A defines a method called hello, which is inherited by B.

Because B does not define a hello method of its own, the original message is printed when b.hello is called.

The following code creates a class by inheriting Python's list class.


class CounterList(list): 
    def __init__(self, *args): 
        super(CounterList, self).__init__(*args) 
        self.counter = 0 #   w  w  w.j  ava 2  s.  com
    def __getitem__(self, index): 
        self.counter += 1 
        return super(CounterList, self).__getitem__(index) 

cl = CounterList(range(10)) 
print cl
cl.reverse() 
print cl 
del cl[3:6] 
print cl 
print cl.counter 
print cl[4] + cl[2] 
print cl.counter 

The code above generates the following result.

CounterList class extends Python list class. Any methods not overridden by CounterList such as append, extend, index may be used directly. In the constructor of CounterList super is used to call the constructor from list.

Inherit from two base classes

We can create a child class by extending more than one parent class. Python allows us to have more than one parent classes.


class Calculator:
    def calculate(self, expression):
        self.value = eval(expression)#  w ww .  j a  va  2  s  .co m

class Talker:
    def talk(self):
        print 'Hi, my value is', self.value

class TalkingCalculator(Calculator, Talker):
    pass




















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules