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 = nameself.employee_id = employee_idself.salary = salarydef 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 = departmentself.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_languageself.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 subclassesmanager1 = Manager("Alice", 1001, 80000, "Engineering")developer1 = Developer("Bob", 2001, 70000, "Python")# Using the objectsprint("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:
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.
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.
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' listanswer.append(animal.description()) # Adds "Nemo is an animal." to 'answer' listanswer.append(dog.speak()) # Adds "Rex says woof!" to 'answer' listanswer.append(dog.description()) # Adds "Rex is an animal." to 'answer' listanswer.append(cat.speak()) # Adds "Misty says meow!" to 'answer' listanswer.append(cat.description()) # Adds "Misty is an animal." to 'answer' listassignment_id ="05-classes-inheritance"question_id ="05_animals_world"submit(student_id, name, assignment_id, str(answer), question_id)