In our previous article, we discussed Python classes and objects. In this article, we will discuss how to inherit the data and methods of one class to another class. Let’s try to look at an example first.
Let’s say we have a class called Person. The Person class contains data such as the name, personal email address, and contact number of a person. And, the class is defined in the following way:
class Person: def __init__(self, name, personal_email, contact_number): self.name = name self.email = personal_email self.contact_number = contact_number def get_email(self): return self.email def get_contact_number(self): return self.contact_number
Here, the __init__() method is the constructor. The constructor will be called every time an object is created for the class Person. The get_email() and get_contact_number() methods are two methods that are defined within the class. Please note that the get_email() method in the Person class returns the personal email address of a person.
Now, let’s say we want to create another class called Employee and the Employee class wants to inherit the data and the methods from the class Person. We can use Python inheritance for this purpose.
In Python, we can create a derived class in the following way:
class Employee(Person):
Here, Employee is a derived class that derives data and methods from the base class Person. If the Person class wants to inherit data and methods from more than one base class, then it can do so in the following way:
0 Comments