Inheritance

Inheritance

Inheritance is a fundamental concept in object-oriented programming that allows us to create a new class based on an existing class, inheriting its attributes and methods. In Python, inheritance is implemented using the syntax:

pythonCopy codeclass ChildClass(ParentClass):
    # additional attributes and methods

Here, ChildClass is the new class we are creating, and ParentClass is the existing class we are inheriting from.

When we create a new instance of ChildClass, it will have all the attributes and methods defined in ParentClass, as well as any additional attributes and methods defined in ChildClass.

For example, let’s say we have a Person class with name and age attributes, and a say_hello() method:

pythonCopy codeclass Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

We can create a new Student class that inherits from Person and adds a school attribute:

pythonCopy codeclass Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

In this example, we call super().__init__(name, age) to call the __init__() method of the Person class, which initializes the name and age attributes. We then add the school attribute to the Student object.

Now, when we create a new Student object, it will have all the attributes and methods defined in the Person class, as well as the school attribute defined in the Student class:

pythonCopy codes = Student("Alice", 18, "High School")
s.say_hello()  # prints "Hello, my name is Alice and I'm 18 years old."
print(s.school)  # prints "High School"

Inheritance allows us to reuse code and avoid duplicating code across multiple classes. It also allows us to create more specific classes that inherit behavior from more general classes.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Get industry recognized certification – Contact us

Menu