Skip to main content
Practice

Inheritance of Class Attributes and Methods

Inheritance is a feature that allows one class to receive the attributes and methods of another class.

This enables the reuse and extension of existing code, improving programming efficiency.

In Python, inheritance is implemented by specifying the parent class inside parentheses when defining a new class.

Inheritance Structure
class ChildClass(ParentClass):
# Contents of the child class

In the code above, ChildClass inherits from ParentClass.

The ChildClass can use the attributes and methods of ParentClass.

The ParentClass is also known as the Superclass or Base class.

The ChildClass is also referred to as the Subclass or Derived class.


Why Use Inheritance?

Inheritance in object-oriented programming serves the following purposes:

  • Code Reusability: It reduces redundancy by utilizing the code of existing classes.

  • Scalability: It allows adding new functionalities or changing existing functionalities without modifying the existing classes.

  • Hierarchical Structure: It creates a hierarchical relationship among classes, which makes the program structure more organized and easier to understand.

Below is an example of defining a Dog class that inherits from the Animal class.

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

def speak(self):
return "Makes a sound."

class Dog(Animal):
def speak(self):
return f"{self.name} barks."

# Example of using the class
my_dog = Dog("Buddy")

print(my_dog.speak())
# Outputs: 'Buddy barks.'

In this example, the Dogclass inherits thenameattribute from theAnimalclass and overrides thespeak method to customize its behavior.

It then overrides the speak method to reflect the characteristics of a dog.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.