Python inheritance is a mechanism that allows a new class to be based on an existing class, inheriting all its attributes and methods. The new class, known as the subclass or derived class, can add new features or override existing ones from the superclass or base class.
This approach promotes code reuse, reduces redundancy, and facilitates maintenance and extensibility of software systems.
In Python, inheritance is implemented through the use of the “class” keyword, followed by the subclass name and the superclass name in parentheses. Multiple inheritance is also supported, where a subclass can inherit from multiple superclasses, separated by commas.
Python Inheritance is a way of creating a new class by inheriting properties and methods of an existing class. The new class created is known as a subclass or derived class and the existing class is known as the superclass or base class.
Here’s an example to explain how inheritance works in Python:
# Define a superclass class Vehicle: def __init__(self, color, speed): self.color = color self.speed = speed def drive(self): print("Driving...") # Define a subclass class Car(Vehicle): def __init__(self, color, speed, model): # calling the superclass constructor super().__init__(color, speed) self.model = model def drive(self): print("Driving a car...") # Create objects of the classes vehicle = Vehicle("Red", 100) car = Car("Blue", 120, "Sedan") # Access superclass methods and attributes print(vehicle.color) # Output: "Red" vehicle.drive() # Output: "Driving..." # Access subclass methods and attributes print(car.color) # Output: "Blue" print(car.model) # Output: "Sedan" car.drive() # Output: "Driving a car..."
Here’s an example of creating a parent class:
class Animal: def __init__(self, name, age): self.name = name self.age = age def make_sound(self): print("This animal makes a sound.") class Dog(Animal): def make_sound(self): print("Woof!") class Cat(Animal): def make_sound(self): print("Meow!") my_dog = Dog("Buddy", 3) my_cat = Cat("Fluffy", 5) print(my_dog.name) # Output: "Buddy" print(my_dog.age) # Output: 3 my_dog.make_sound() # Output: "Woof!" print(my_cat.name) # Output: "Fluffy" print(my_cat.age) # Output: 5 my_cat.make_sound() # Output: "Meow!"
You can create as many derived classes as you need, and each one will have access to all the attributes and methods of the parent class.
Here’s an example of creating a child class:
class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start(self): print("The vehicle is starting.") class Car(Vehicle): def __init__(self, make, model, year, doors): super().__init__(make, model, year) self.doors = doors def start(self): print("The car is starting.") class Truck(Vehicle): def __init__(self, make, model, year, payload): super().__init__(make, model, year) self.payload = payload def load(self): print("The truck is loading cargo.") my_car = Car("Toyota", "Corolla", 2020, 4) my_truck = Truck("Ford", "F-150", 2018, 1500) print(my_car.make) # Output: "Toyota" print(my_car.doors) # Output: 4 my_car.start() # Output: "The car is starting." print(my_truck.make) # Output: "Ford" print(my_truck.payload) # Output: 1500 my_truck.start() # Output: "The vehicle is starting." my_truck.load() # Output: "The truck is loading cargo."
You can create as many child classes as you need, and each one will have access to all the attributes and methods of the parent class.
To add the __init__() function to a class, you define it within the class definition like this:
class MyClass: def __init__(self, attribute1, attribute2): self.attribute1 = attribute1 self.attribute2 = attribute2
Here’s an example of using the __init__() function to create a Person class:
class Person: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def greet(self): print("Hello, my name is", self.name) person1 = Person("Alice", 25, "female") person2 = Person("Bob", 30, "male") print(person1.name) # Output: "Alice" print(person1.age) # Output: 25 print(person1.gender) # Output: "female" person1.greet() # Output: "Hello, my name is Alice" person2.greet() # Output: "Hello, my name is Bob"
Here’s an example of using the super() function to call a parent class’s method:
class Parent: def my_method(self): print("This is the parent class.") class Child(Parent): def my_method(self): super().my_method() # call the parent class's method print("This is the child class.") child = Child() child.my_method() # Output: "This is the parent class." "This is the child class."
Here’s an example:
class Parent: def __init__(self, attribute1): self.attribute1 = attribute1 class Child(Parent): def __init__(self, attribute1, attribute2): super().__init__(attribute1) # initialize the parent class's attribute self.attribute2 = attribute2 child = Child("value1", "value2") print(child.attribute1) # Output: "value1" print(child.attribute2) # Output: "value2"
Add Properties
In Python, properties allow you to define getters, setters, and deleters for class attributes.
Here’s an example:
class Person: def __init__(self, name, age): self._name = name self._age = age @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("Age must be positive.") self._age = value @age.deleter def age(self): del self._age
The age deleter method deletes the _age attribute.
Here’s an example of using the Person class with its properties:
person = Person("Alice", 25) print(person.name) # Output: "Alice" person.name = "Bob" print(person.name) # Output: "Bob" print(person.age) # Output: 25 person.age = 30 print(person.age) # Output: 30 del person.age print(person.age) # Raises AttributeError: 'Person' object has no attribute '_age'
class Person: def __init__(self, name, age): self._name = name self._age = age @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("Age must be positive.") self._age = value @age.deleter def age(self): del self._age
Add Methods
Methods can be added to a class to perform specific actions or operations. To add a method to a class, you simply define it within the class definition.
Here’s an example:
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height)
Here’s an example of using the Rectangle class with its methods:
rectangle = Rectangle(10, 5) print(rectangle.area()) # Output: 50 print(rectangle.perimeter()) # Output: 30 here's another example of a class with methods: class BankAccount: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if self.balance >= amount: self.balance -= amount else: print("Insufficient funds.") def display_balance(self): print(f"Current balance: {self.balance}")
Here’s an example of using the BankAccount class with its methods:
account = BankAccount(1000) account.display_balance() # Output: "Current balance: 1000" account.deposit(500) account.display_balance() # Output: "Current balance: 1500" account.withdraw(2000) # Output: "Insufficient funds." account.display_balance() # Output: "Current balance: 1500" account.withdraw(1000) account.display_balance() # Output: "Current balance: 500"
Types of Inheritance with examples
Here are a few more examples to illustrate Python Inheritance:
Single Inheritance
class Animal: def __init__(self, name, species): self.name = name self.species = species def move(self): print(f"{self.name} is moving...") class Dog(Animal): def bark(self): print(f"{self.name} is barking...") my_dog = Dog("Buddy", "Golden Retriever") print(my_dog.species) # Output: "Golden Retriever" my_dog.move() # Output: "Buddy is moving..." my_dog.bark() # Output: "Buddy is barking..."
Example:
Single inheritance is a type of inheritance where a derived class inherits from a single base class.
class Vehicle: def __init__(self, name, color): self.name = name self.color = color def drive(self): print(f"{self.name} is driving...") class Car(Vehicle): def __init__(self, name, color, model): super().__init__(name, color) self.model = model my_car = Car("BMW", "Black", "X5") print(my_car.model) # Output: "X5" my_car.drive() # Output: "BMW is driving..."
Multiple inheritance is a type of inheritance where a derived class inherits from multiple base classes.
class Animal: def __init__(self, name): self.name = name def move(self): print(f"{self.name} is moving...") class Pet: def __init__(self, owner): self.owner = owner def play(self): print(f"{self.owner} is playing with {self.name}...") class Dog(Animal, Pet): def bark(self): print(f"{self.name} is barking...") my_dog = Dog("Buddy", "John") my_dog.move() # Output: "Buddy is moving..." my_dog.play() # Output: "John is playing with Buddy..." my_dog.bark() # Output: "Buddy is barking..."
Hierarchical inheritance is a type of inheritance where a derived class inherits from a single base class, and multiple derived classes can inherit from the same base class.
class Shape: def __init__(self, name): self.name = name def area(self): pass class Circle(Shape): def __init__(self, name, radius): super().__init__(name) self.radius = radius def area(self): return 3.14 * self.radius ** 2 class Rectangle(Shape): def __init__(self, name, length, breadth): super().__init__(name) self.length = length self.breadth = breadth def area(self): return self.length * self.breadth my_circle = Circle("Circle", 5) my_rectangle = Rectangle("Rectangle", 4, 6) print(my_circle.area()) # Output: 78.5 print(my_rectangle.area()) # Output: 24
Hybrid inheritance is a combination of multiple inheritance and multi-level inheritance.
class Vehicle: def __init__(self, name): self.name = name def drive(self): print(f"{self.name} is driving...") class Car(Vehicle): def __init__(self, name, model): super().__init__(name) self.model = model class Electric: def __init__(self, name, battery): self.name = name self.battery = battery def charge(self): print(f"{self.name} is charging...") class ElectricCar(Car, Electric): def __init__(self, name, model, battery): Car.__init__(self, name, model) Electric.__init__(self, name, battery) my_electric_car = ElectricCar("Tesla", "Model S", "100 kWh") my_electric_car.drive() # Output: "Tesla is driving..." my_electric_car.charge() # Output: "Tesla is charging..."
Example:
Hybrid inheritance is a combination of multiple types of inheritance. It is a complex type of inheritance that involves multiple base classes and multiple derived classes.
class A: def foo(self): print("A") class B(A): def foo(self): print("B") class C(A): def foo(self): print("C") class D(B, C): pass class E: def bar(self): print("E") class F(D, E): pass my_f = F() my_f.foo() # Output: "B" my_f.bar() # Output: "E"
Method Resolution Order (MRO) is the order in which Python looks for methods to execute in a class hierarchy. It is used to determine which method to call when a method is called on an instance of a class.
class A: def foo(self): print("A") class B(A): def foo(self): print("B") class C(A): def foo(self): print("C") class D(B, C): pass my_d = D() my_d.foo() # Output: "B"
An abstract base class (ABC) is a class that cannot be instantiated, and is only meant to be subclassed. ABCs are used to define a common interface for a group of subclasses, and to enforce the implementation of certain methods in those subclasses.
from abc import ABC, abstractmethod
class Animal(ABC): def __init__(self, name): self.name = name @abstractmethod def move(self): pass class Dog(Animal): def move(self): print(f"{self.name} is running...") class Cat(Animal): def move(self): print(f"{self.name} is walking...") # This will raise a TypeError because Animal is an abstract class my_animal = Animal("Some Animal") my_dog = Dog("Buddy") my_dog.move() # Output: "Buddy is running..." my_cat = Cat("Fluffy") my_cat.move() # Output: "Fluffy is walking..."
a) A way to create new classes from existing classes
b) A way to create new instances from existing classes
c) A way to create new methods from existing classes
d) A way to create new attributes from existing classes
a) extend
b) inherit
c) include
d) super
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Hybrid inheritance
a) new()
b) init()
c) str()
d) repr()
a) super()
b) parent()
c) base()
d) ancestor()
Answers:
1-a 2-a 3-b 4-b 5-a
a) issubclass()
b) superclass()
c) parentclass()
d) childclass()
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Inheritance with extension
a) new()
b) init()
c) str()
d) repr()
a) new()
b) init()
c) str()
d) repr()
a) final
b) override
c) prevent
d) None of the above
Answers: 6-a 7-d 8-d 9-c 10-a
a) isclass()
b) isinstance()
c) type()
d) class()
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Inheritance without extension
a) super()
b) parent()
c) base()
d) ancestor()
a) new()
b) init()
c) str()
d) copy()
a) extend
b) inherit
c) include
d) None of the above
Answers:11-b 12-a 13-a 14-d 15-d
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Overriding inheritance
a) delete()
b) remove()
c) delattr()
d) deleteattr()
a) compare()
b) equal()
c) cmp()
d) eq()
a) new()
b) init()
c) str()
d) deepcopy()
a) extend
b) inherit
c) include
d) None of the above
Answers:16-d 17-c 18-d 19-d 20-b
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Overriding inheritance
a) new()
b) init()
c) str()
d) copy()
a) len()
b) size()
c) length()
d) count()
a) call()
b) operation()
c) operator()
d) add()
a) private
b) protected
c) public
d) None of the above
Answers: 21-b 22-a 23-a 24-d 25-b
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Overriding inheritance
a) new()
b) init()
c) str()
d) copy()
a) len()
b) size()
c) length()
d) count()
a) call()
b) operation()
c) operator()
d) add()
a) private
b) protected
c) public
d) None of the above
Answers: 26- b 27-a 28-a 29-d 30-b
a) Single inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Overriding inheritance
a) delete()
b) remove()
c) delattr()
d) deleteattr()
a) compare()
b) equal()
c) cmp()
d) eq()
a) new()
b) init()
c) str()
d) deepcopy()
a) extend
b) inherit
c) include
d) None of the above
Answers:31-d 32-c 33-d 34-d 35-b