Python Inheritance: Reusing Code with Parent and Child Classes

Posted by Anonymous and classified in Mathematics

Written on in English with a size of 3.34 KB

Understanding Inheritance in Python

Inheritance allows a class to use and extend the properties and methods of another class. It promotes code reusability and reduces duplication. Think of it as “child learns from parent.” 👨‍👦‍💻

Code Duplication: Program Without Inheritance

When classes share common attributes or methods (such as first_name, last_name, and get_age), implementing them separately leads to redundant code, as shown below:

import datetime

class TennisPlayer:
    def __init__(self, fname, lname, birth_year):
        self.first_name = fname
        self.last_name = lname
        self.birth_year = birth_year
        self.aces = []

    def get_age(self):
        now = datetime.datetime.now()
        return now.year - self.birth_year

    def get_average_aces_per_match(self):
        return sum(self.aces) / len(self.aces)

    def add_ace(self, num_aces):
        self.aces.append(num_aces)


class CricketPlayer:
    def __init__(self, fname, lname, team, birth_year):
        self.first_name = fname
        self.last_name = lname
        self.birth_year = birth_year
        self.team = team
        self.scores = []

    def get_age(self):
        now = datetime.datetime.now()
        return now.year - self.birth_year

    def add_score(self, score):
        self.scores.append(score)

    def get_average_score(self):
        return sum(self.scores) / len(self.scores)


virat = CricketPlayer('virat', 'kohli', 'india', 1988)
virat.add_score(37)
virat.add_score(23)
virat.add_score(85)

print("Age of virat kohli:", virat.get_age())
print("Average score of virat kohli:", virat.get_average_score())

roger = TennisPlayer('roger','federer',1981)
roger.add_ace(5)
roger.add_ace(7)
print("Age of roger federer:", roger.get_age())

Implementing Code Reusability with Inheritance

By creating a base Player class, we can move the common attributes (name, birth year) and methods (get_age) into the parent class. The specialized classes (TennisPlayer and CricketPlayer) then inherit these features, significantly reducing redundancy.

import datetime

class Player:
    def __init__(self, fname, lname, birth_year):
        self.first_name = fname
        self.last_name = lname
        self.birth_year = birth_year

    def get_age(self):
        now = datetime.datetime.now()
        return now.year - self.birth_year

class TennisPlayer(Player):
    def __init__(self, fname, lname, birth_year):
        super().__init__(fname, lname, birth_year)
        self.aces = []

    def get_average_aces_per_match(self):
        return sum(self.aces) / len(self.aces)

class CricketPlayer(Player):
    def __init__(self, fname, lname, team, birth_year):
        super().__init__(fname, lname, birth_year)
        self.team = team
        self.scores = []

    def add_score(self, score):
        self.scores.append(score)

    def get_average_score(self):
        return sum(self.scores) / len(self.scores)

virat = CricketPlayer('virat', 'kohli', 'india', 1988)
virat.add_score(37)
virat.add_score(23)
virat.add_score(85)

print("Age of virat kohli:", virat.get_age())
print("Average score of virat kohli:", virat.get_average_score())

roger = TennisPlayer('roger','federer',1981)
print("Age of roger federer:", roger.get_age())

Related entries: