Inheritance

Inheritance is a way to create a derived class from a base class. The derived class will inherit all the attributes and methods from the base class.

class Employee:
    def __init__(self, name, employee_id, salary):
        self.name = name
        self.employee_id = employee_id
        self.salary = salary

    def display_info(self):
        print(f"Employee ID: {self.employee_id}\nName: {self.name}\nSalary: ${self.salary}")

class Manager(Employee):
    def __init__(self, name, employee_id, salary, department):
        super().__init__(name, employee_id, salary)
        self.department = department
        self.projects = []

    def display_info(self):
        super().display_info()
        print(f"Department: {self.department}\nRole: Manager")

    def add_project(self, project_name):
        self.projects.append(project_name)
        print(f"{self.name} added a new project: {project_name}")

    def manage_team(self):
        print(f"{self.name} is managing the team and projects.")

class Developer(Employee):
    def __init__(self, name, employee_id, salary, programming_language):
        super().__init__(name, employee_id, salary)
        self.programming_language = programming_language
        self.tasks = []

    def display_info(self):
        super().display_info()
        print(f"Programming Language: {self.programming_language}\nRole: Developer")

    def add_task(self, task_name):
        self.tasks.append(task_name)
        print(f"{self.name} added a new task: {task_name}")

    def write_code(self):
        print(f"{self.name} is writing code for the project.")

# Creating instances of the subclasses
manager1 = Manager("Alice", 1001, 80000, "Engineering")
developer1 = Developer("Bob", 2001, 70000, "Python")

# Using the objects
print("Manager Information:")
manager1.display_info()
manager1.add_project("Project A")
manager1.manage_team()

print("\nDeveloper Information:")
developer1.display_info()
developer1.add_task("Feature X")
developer1.write_code()
Manager Information:
Employee ID: 1001
Name: Alice
Salary: $80000
Department: Engineering
Role: Manager
Alice added a new project: Project A
Alice is managing the team and projects.

Developer Information:
Employee ID: 2001
Name: Bob
Salary: $70000
Programming Language: Python
Role: Developer
Bob added a new task: Feature X
Bob is writing code for the project.

As you can see above we can create different type of employees by inheriting from the base class Employee, now we have a Developer and a Manager class. This concept of inheritance is very useful like what we can see in the example above, developers and managers are both employees, so they can share the same attributes and methods from the base class Employee, but still they have their own attributes and methods that are unique to them when needed.

Parent and child

In object oriented programming when a class inherits from another class, the class that inherits is called the child class and the class that is being inherited from is called the parent class. The syntax is pretty simple:

# Create python parent and child

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print(f"Name: {self.name}\nAge: {self.age}")

class Student(Person):
    def __init__(self, name, age, student_id, major):
        super().__init__(name, age)
        self.student_id = student_id
        self.major = major

student = Student("Alice", 20, 1001, "Computer Science")
student.display_info()
Name: Alice
Age: 20

Overriding parent methods

Sometimes we want to change the behavior of a method that is inherited from the parent class. We can do this by overriding the method in the child class.

# Create python parent and child

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print(f"Name: {self.name}\nAge: {self.age}")

class Student(Person):
    def __init__(self, name, age, student_id, major):
        super().__init__(name, age)
        self.student_id = student_id
        self.major = major
    
    def display_info(self):
        print(f"Name: {self.name}\nAge: {self.age}\nStudent ID: {self.student_id}\nMajor: {self.major}")

student = Student("Alice", 20, 1001, "Computer Science")
student.display_info()

super()

super() is a function that allows us to use the parent class methods and attributes. When we call super() we are calling the parent class and we can access its methods and attributes.

# Create python parent and child

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def display_info(self):
        print(f"Name: {self.name}\nAge: {self.age}")

class Student(Person):
    def __init__(self, name, age, student_id, major):
        super().__init__(name, age)
        self.student_id = student_id
        self.major = major
    
    def display_info(self):
        super().display_info()
        print(f"Student ID: {self.student_id}\nMajor: {self.major}")

student = Student("Alice", 20, 1001, "Computer Science")
student.display_info()
Name: Alice
Age: 20
Student ID: 1001
Major: Computer Science

As we can see above that we call the parent’s class display_info() method in our overridden method display_info(), it makes us possible to use the parent’s class method and add some extra functionality to it rather than rewriting the whole method.

Exercise

# @title #### 05. Animals World

# In this assignment, you will reinforce your understanding of inheritance in Python. 

# Here are the specific tasks for this assignment:
# 1. Create a parent class named 'Animal' with an attribute 'name'.
# 2. Add two methods to the 'Animal' class:
#     a. `speak`: This should return a string "{name} makes a sound". 
#     b. `description`: This should return a string "{name} is an animal". 
# 
# 3. Create two child classes that inherit from Animal class, 'Dog' and 'Cat'.
# 4. Both 'Dog' and 'Cat' classes should use the `super()` function to inherit the name attribute from the Animal class.
# 5. Both 'Dog' and 'Cat' classes should override the 'speak' method from the Animal class.
#     a. For 'Dog' class, the 'speak' method should return "{name} says woof!"
#     b. For 'Cat' class, the 'speak' method should return "{name} says meow!"
# 
# Remember, the `description` method in the 'Animal' class should not be overridden in child classes.
# 
# At the end of your implementation, create instances of Animal, Dog, and Cat, and call their 'speak' and 'description' methods. Append all outputs to an 'answer' list and submit this list as your assignment.
# 
# Here is an example of what your code should emulate but not limited to:
animal = Animal("Nemo")
dog = Dog("Rex")
cat = Cat("Misty")
answer = []
answer.append(animal.speak()) # Adds "Nemo makes a sound" to 'answer' list
answer.append(animal.description()) # Adds "Nemo is an animal." to 'answer' list
answer.append(dog.speak()) # Adds "Rex says woof!" to 'answer' list
answer.append(dog.description()) # Adds "Rex is an animal." to 'answer' list
answer.append(cat.speak()) # Adds "Misty says meow!" to 'answer' list
answer.append(cat.description()) # Adds "Misty is an animal." to 'answer' list
assignment_id = "05-classes-inheritance"
question_id = "05_animals_world"
submit(student_id, name, assignment_id, str(answer), question_id)
Back to top