python
  1. python-inheritance

Python Inheritance

Inheritance is a process in which one class inherits properties and behavior of another class. The class which inherits the properties of another class is called the derived class or child class, and the class whose properties are inherited by the child class is called the base class or parent class.

Syntax

The basic syntax for deriving a class is as follows:

class ChildClassName(ParentClassName):
    # attributes and methods of child class

Example

class Animal:
    def __init__(self, name, type):
        self.name = name
        self.type = type

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, "Dog")
        self.breed = breed

d = Dog("Max", "Labrador")
print(d.name)   # Output: Max
print(d.type)   # Output: Dog
print(d.breed)  # Output: Labrador

Explanation

In the above example, the Animal class is the parent class and the Dog class is the child class. The Dog class is derived from the Animal class using the Animal class as the base class. The Dog class inherits the name and type attributes from the Animal class and is able to access them using the super() function. In addition to these attributes, the Dog class also has a breed attribute which is specific to the Dog class.

Use

Inheritance is used to create new classes that are built upon existing classes. The child class can inherit all the attributes and methods of the parent class, and it can also add new attributes and methods to itself. Inheritance makes the code more modular and reusable.

Important Points

  • Inheritance creates a parent-child relationship between two classes.
  • The child class inherits all the properties of the parent class.
  • The child class can add its own properties and methods to itself.

Summary

Inheritance is an important feature of object-oriented programming that allows one class to inherit properties and behavior from another class. It helps to create code that is more modular and reusable. In Python, inheritance can be implemented by using the class keyword and specifying the parent class in parentheses after the name of the child class.

Published on: