A better example of Class Inheritance in Python

Lots of people ask me, why should they use classes at all ? Well. I think its about control, and ease . It solves the headache of data sharing and accessibility. I am going to show you an example , which hopefully proves that classes and fundamentals like inheritance  are brilliant.

Example:

I have  two classes in the below program. Person and Manager . Manager has inherited the Person class (because he is a person too....almost (lol)) .


class Person:
    def __init__(self, name, job, pay=0):
        self.name = name
        self.job = job
        self.pay = pay

    def lastName(self):
        return self.name.split()[-1]

    def giveRaise(self, percent):
        self.pay = int(self.pay * (1 + float(percent)/100))

    def __str__(self):
        return '[Person: %s, %s]' % (self.name, self.pay)

class Manager(Person):
    def giveRaise(self, percent):
        self.pay = int(self.pay * (1 + ((float(percent)+10)/100)))

The only diff between a Manager is , he gets an extra 10% hike on every raise. (Don't argue now about this ). Let try creating some objects.


>>> bob = Person('Bob Marley', 'Architech', 10000)
>>> bob.giveRaise(15)
>>> print bob
[Person: Bob Marley, 11500]
>>> boss = Manager('Big Boss', 'Tech Manager', 200000)
>>> boss.giveRaise(10)
>>> print boss
[Person: Big Boss, 240000]

Notice that the function 'giveRaise' is almost a copy of the Person.giveRaise function. If we create more like this, essentially we have to copy its code every time and tweak it.

What we really are looking for, is a way to somehow augment the original giveRaise, instead of replacing it altogether. This is the good way to do this:


class Manager(Person):
    def giveRaise(self, percent, bonus=10):
        Person.giveRaise(self, percent + bonus)

This will give us the same result.

OK...This looks good. But we can improvise on this. You may ask. We ALREADY KNOW that a MANAGER job is 'MANAGER'. Still we are creating the Manager class by passing the job title as 'Tech Manager'. This is unnecessary. So lets do something about it. We are going to use the same principle as above. Use the already existing __init__ of the Person class.


>>> adam = Person('adam west', 'Analyst', 10000)
>>> adam.lastName()
'west'
>>> adam.giveRaise(10)
>>> adam.pay
11000
>>> print adam
[Person: adam west, 11000]
>>> paul = Manager('Paul McGill', 15000)
>>> paul.lastName()
'McGill'
>>> paul.giveRaise(10)
>>> paul.pay
18000
>>> paul.job
'Manager'


Popular posts from this blog

Why should you visit Kashmir sooner?

CNTLM in Office

How to run a Python program over the internet?