When and how to use super keyword

Use super keyword

The super function is used to call methods from the parent class.


class Bird(object):
    def __init__(self):
       self.hungry = 1#   w ww.jav  a2s  .c om
    def eat(self):
       if self.hungry == 1: 
          print 'hungry...'
          self.hungry = 0
       else: 
          print 'No, thanks!'

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

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

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules