What is Object Inheritance
Object inheritance is a fundamental concept in object-oriented programming(OOP), a programming standard used within Python. It creates new classes (child classes) based on existing classes (base classes), inheriting their attributes and methods. This facilitates the creation of a hierarchy of classes, where child classes can reuse and create new functionality of parent classes. In Python, object inheritance is created by using the ‘class’ keyword and with the parent classes in parenthese. Object inheritance provides code reusability, hierarchy and organization, and polymorphism which are critical in software development.
Base and Derived Class
- Base Class (Parent Class): This class provides attributes and methods that can be inherited by other classes.
- Derived Class (Child Class): This is the class that inherits attributes and methods from the base class. This class can also add new attributes and methods to extend functionality of the code.
Benefits of Object Inheritance
- Code Reusability: Object Inheritance promotes reuse of existing codes. When there are common methods or attributes used between multiple classes, you can put it into a base class. Then have multiple derived classes inherit and extend the functionality.
- Hierarchy and Organization: Object inheritance allows you to create complex models by creating hierarchy of related classes, improving organization and DRY code.
- Polymorphism: This is a fundamental concept in object oriented programming (OOP) that allows objects of different classes to be treated as objects of a common class. You can define a base class with common attributes and methods and then have multiple derived classes inherit from the base class implementing those methods from the base class differently, adjusting to the behaviors it’s needed for that class. Polymorphism can also work with functions, as functions can accept objects of different classes as arguments and perform operations based on the object’s attributes and methods.
Defining Base and Derived class
You can create a base class by defining a class with attributes and methods. To create the derived class, use ‘class’ keyword followed by the derived class name and then the base class name in parentheses.
In this example, the ‘Dog’ class inherits the ‘init’ constructor and the ‘speak’ from the ‘Animal’ class.
Overriding inherited Methods
Derived classes can override methods inherited from the base classes to provide their own functionality. In the ‘Dog’ class example, the ‘speak’ method can be overridden to provides its own specific functionality.
Extending Functionality
Derived classes can add new attributes and methods to extend the functionality inherited from the base class. This allows different behavior within each classes.



Top comments (0)