Home > Enterprise >  What's the point of method inheritance and calling Parent.method()?
What's the point of method inheritance and calling Parent.method()?

Time:12-31

I came across this example of method inheritance:

The child Manager class inherits from the parent Employee class, and modifies its give_raise() method, while also calling Employee.give_raise() in the new implementation.

# Parent class
class Employee:
    def __init__(self, name, salary=30000):
        self.name = name
        self.salary = salary

    def give_raise(self, amount):
        self.salary  = amount

# Child class         
class Manager(Employee):
    def display(self):
        print("Manager ", self.name)

    def __init__(self, name, salary=50000, project=None):
        Employee.__init__(self, name, salary)
        self.project = project

    # Modify the give_raise method
    def give_raise(self, amount, bonus=1.05):
        new_amount = amount * bonus

        # Call the parent method
        Employee.give_raise(self, new_amount)
    
    
mngr = Manager("John Smith", 80000)
mngr.give_raise(5000)
print(mngr.salary)

My question is: isn't this a bit convoluted?

I get class inheritance. But calling a parent method within a child method of the same name?

Wouldn't it be better to write give_raise() in the Manager class as:

def give_raise(self, amount, bonus):
        new_amount = amount * bonus
        self.salary  = amount

To me, it only makes sense to call Parent.method() if it's a completely different method that requires a lot of lines of code

CodePudding user response:

Parent.give_raise could be defined in a way that doesn't require it to be overriden in order to customize what raise different employee types get.

For example,

class Employee:
    default_salary = 30000

    def __init__(self, name, salary=None, bonus=1, **kwargs):
        super().__init__(**kwargs)
        if salary is None:
            salary = self.default_salary

        self.name = name
        self.salary = salary
        self.bonus_multiplier = bonus

    def give_raise(self, amount):
        self.salary  = amount * self.bonus_multiplier


class Manager(Employee):
    default_salary = 50000

    def display(self):
        print("Manager ", self.name)

    def __init__(self, *, project=None, **kwargs):
        if 'bonus' not in kwargs:
            kwargs['bonus'] = 1.05
        super.__init__(**kwargs)
        self.project = project


mngr = Manager(name="John Smith", salary=80000)
mngr.give_raise(5000)
print(mngr.salary)

CodePudding user response:

I agree with you initial question in that the implementations are a bit convoluted and don't help to clearly convey the intended usage. The main goal of method inheritance is to encourage reusable, encapsulated behavior within the class hierarchy. That way the derived class could add some functionality or override the underlying functionality (or leave it be and add other functionality).

  • Related