Python: Super class examples

Hi all. We are going to see some examples of usage of keyword 'super' here . 

Below code shows two classes Employee and Developer. A parent and a child.


class Employee(object):
    def __init__(self, first, last):
        self.first = first
        self.last = last
        print 'Employee: {0}, {1}'.format(first, last)

    def hike_category(self):
        hike = 0
        if self.grade == 'A':
            hike = (0.1*self.pay) + self.pay #percent
        elif self.grade == 'B':
            hike = (0.15*self.pay) + self.pay #percent
        elif self.grade == 'C':
            hike = (0.20*self.pay) + self.pay #percent
        return '{0},{1} gets {2}'.format(self.first, self.last, hike)

class Developer(Employee):
    def __init__(self, fname, lname, grade, pay):
        super(Developer, self).__init__(fname, lname)
        self.grade = grade
        self.pay = pay

Lets run the above program.

Results:

>>> d = Developer('arc', 'roy', 'C', 10000)
Employee: arc, roy
>>> d.hike_category()
'arc,roy gets 12000.0'


Observations and things to note


  • Above programming is done in Python 2.7. 
  • In 2.7, the class needs to inherit from object , otherwise it wont work.
  • The variable names can be different in both classes (In 2.7 only).
  • super needs to have same class name as first argument. 
  • The class instance 'b' can access all class variables of both classes.


Popular posts from this blog

Why should you visit Kashmir sooner?

CNTLM in Office

How to run a Python program over the internet?