How to override a constructor

Override constructor

We can override a constructor during the class inheritance.

If you override the constructor of a class, you need to call the constructor of the superclass.


class Bird: #  ww  w  .  j av  a 2  s .  com
    def __init__(self): 
        self.hungry = 1 
    def eat(self): 
        if self.hungry: 
            print 'Full' 
            self.hungry = 0 
        else: 
            print 'No, thanks!' 

b = Bird() 
b.eat() 
b.eat() 


class SongBird(Bird): 
    def __init__(self): 
        Bird.__init__(self) 
        self.sound = 'Squawk!' 
    def sing(self): 
        print self.sound 


sb = SongBird() 
sb.sing() 
sb.eat() 
sb.eat() 

The code above generates the following result.

Calling Superclass Constructors


class Super:#  w  w w .  ja v  a  2 s .  c  o  m
    def __init__(self, x):
        print "super" + x

class Sub(Super):
    def __init__(self, x, y):
        Super.__init__(self, x) 




















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules