Understanding Inheritance: A Guide to Python's Attribute and Method Inheritance

Introduction

Hello again! In this part of our Python Class Basics Revision, we delve into inheritance in object-oriented programming (OOP) with Python. Inheritance allows us to share code across classes, thus improving readability and efficiency.

In this lesson, we'll clarify attribute and method inheritance in Python using practical examples. Our lesson's blueprint includes defining inheritance, examining attribute inheritance, exploring method inheritance, and decoding the super() function in Python. Ready? Let's get started!

Defining Inheritance

Inheritance involves creating a child class that inherits details from a parent class. In Python, we often find scenarios where classes share common attributes or methods, which makes inheritance highly useful.

Here's an example featuring a parent class named Vehicle and a child class named Car:

Python
# Define the parent class 'Vehicle'
class Vehicle:
    # Initialize the Vehicle with color and brand attributes
    def __init__(self, color, brand):
        self.color = color
        self.brand = brand

# Define the child class 'Car', inheriting from 'Vehicle'
class Car(Vehicle):
    def __init__(self, color, brand, doors):
        # Call the parent class's __init__ method to set color and brand
        super().__init__(color, brand)
        self.doors = doors

Inheritance types, such as Single, Multiple, Multilevel, and Hierarchical, in Python, cater to different needs. However, our focus in this lesson is primarily on single inheritance, where one parent class feeds one child class.

Attribute Inheritance

Attribute inheritance allows a child class to inherit the attributes of a parent class.

Consider this example featuring a parent class named Artist, and a child class named Musician:

class Artist:
    def __init__(self, name):
        self.name = name   # Parent's attribute

class Musician(Artist):
    def __init__(self, name, instrument):
        super().__init__(name)   # Inheriting parent's attribute
        self.instrument = instrument   # Child's own attribute

john = Musician('John Lennon', 'Guitar')  # Creating a Musician instance
print(john.name)   # Output: John Lennon
print(john.instrument)   # Output: Guitar

The Musician class inherits the name attribute from the Artist class, and also has its own unique attribute, instrument.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal