Python Inheritance
The benefits of inheritance are:
● It represents real-world relationships well.
● It provides the reusability of a code. We don’t have to write the same code again and again. Also, it allows us toadd more features to a class without modifying it.
● It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
Types of Inheritance
Example:
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f”{self.name} makes a sound.”
# Derived class
class Dog(Animal):
def speak(self):
return f”{self.name} barks.”
# Creating an instance of the derived class
my_dog = Dog(“Tommy”)
print(my_dog.speak())
Output:
Tommy barks.
Explanation:
class Animal:
This defines a class called Animal. It’s the base class (or parent class) from which other
classes will inherit.
def __init__(self, name):
self.name = name
This is the constructor method __init__. It’s automatically called when an instance of the
class is created.
The method takes one argument name, in addition to self, which refers to the instance of
the class.
The line self.name = name assigns the value of the parameter name to the instance
attribute name. This means that each instance of Animal will have its own name
attribute.
def speak(self):
return f”{self.name} makes a sound.”
This defines a method called speak for the Animal class.
The method returns a string that includes the instance’s name (self.name) and a generic message “makes a sound.”. This is a general method that could be used for any animal, but it’s not specific to any animal sound.
class Dog(Animal):
This defines a new class Dog, which inherits from the Animal class. This means Dog will have access to the methods and attributes of Animal.
def speak(self):
return f”{self.name} barks.”
This method overrides the speak method from the base class Animal.
In this case, when the speak method is called on an instance of Dog, it will return a
message specific to a dog, using the dog’s name and the word “barks”.
my_dog = Dog(“Tommy”)
Here, we are creating an instance of the Dog class and passing the name “Tommy” to the constructor.
The __init__ method from the Animal class is called because Dog inherits from Animal. This means that “Tommy” is assigned to the name attribute of the my_dog instance.
print(my_dog.speak())
The speak method is called on the my_dog instance. Since Dog overrides the speak method from Animal, the method from Dog is used.
● Multilevel Inheritance: Multi-level inheritance enables a derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class.
Example:
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f”{self.name} makes a sound.”
# Derived class (inherits from Animal)
class Dog(Animal):
def speak(self):
return f”{self.name} barks.”
# Further derived class (inherits from Dog)
class Puppy(Dog):
def play(self):
return f”{self.name} is playing.”
# Creating an instance of the most derived class
my_puppy = Puppy(“Charlie”)
print(my_puppy.speak())
print(my_puppy.play())
Explanation:
class Animal:
This line defines a base class named Animal. It serves as the foundation for other
classes to inherit from.
def __init__(self, name):
self.name = name
__init__ is the constructor method that initializes a new instance of the Animal class.
It takes name as an argument and assigns it to the instance variable self.name, which will hold the name of the animal.
def speak(self):
return f”{self.name} makes a sound.”
This method defines the behavior of the speak action for the Animal class. It returns a string indicating that the animal makes a sound, using the animal’s name stored in self.name.
class Dog(Animal):
This line defines a derived class named Dog that inherits from the Animal class. This
means that Dog will have all the properties and methods of Animal.
def speak(self):
return f”{self.name} barks.”
The Dog class overrides the speak method inherited from Animal. Instead of saying the animal makes a sound, it specifies that a dog barks.
class Puppy(Dog):
This line defines another derived class named Puppy that inherits from the Dog class. Thus, Puppy inherits the properties and methods of both Dog and Animal.
def play(self):
return f”{self.name} is playing.”
This method defines a new behavior specific to the Puppy class. It returns a string indicating that the puppy is playing, utilizing the name of the puppy stored in self.name.
my_puppy = Puppy(“Charlie”)
This line creates an instance of the Puppy class named my_puppy, with the name “Charlie”. The constructor of Puppy calls the constructor of Dog, which in turn calls the constructor of Animal. As a result, self.name is set to “Charlie” for this instance.
print(my_puppy.speak())
When my_puppy.speak() is called, it prints “Charlie barks.”, demonstrating the behavior defined in the Dog class.
print(my_puppy.play())
● Hierarchical Inheritance: Hierarchical-level inheritance enables more than one derived class to inherit properties from a parent class.
Example:
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f”{self.name} makes a sound.”
# Derived class 1 (inherits from Animal)
class Dog(Animal):
def speak(self):
return f”{self.name} barks.”
# Derived class 2 (inherits from Animal)
class Cat(Animal):
def speak(self):
return f”{self.name} meows.”
# Creating instances of the derived classes
my_dog = Dog(“Buddy”)
my_cat = Cat(“Whiskers”)
print(my_dog.speak())
print(my_cat.speak())
Explanation:
class Animal:
This defines a class named Animal, which will act as the base class or parent class. Other classes will inherit from this class.
def __init__(self, name):
self.name = name
This is the constructor method __init__. It initializes the name attribute of the class when an object is created.
The self parameter represents the instance of the class, and name is the argument provided during instantiation. self.name = name assigns the provided name value to the instance attribute name.
def speak(self):
return f”{self.name} makes a sound.”
This method named speak is a general method for the Animal class. It returns a string indicating that the animal makes a generic sound.
The string uses f-string formatting to include the name attribute of the instance, which will be specific to the object created.
class Dog(Animal):
This defines a class Dog that inherits from the Animal class. Inheritance allows the Dog class to inherit the properties (attributes) and methods of Animal.
def speak(self):
return f”{self.name} barks.”
This method overrides the speak method in the Animal class. Instead of the generic message from Animal, the Dog class provides its specific implementation, returning a string where the dog barks.
It still uses self.name to include the name of the dog in the string.
class Cat(Animal):
This defines a class Cat that also inherits from the Animal class. Like Dog, it inherits the name attribute and methods from Animal.
def speak(self):
return f”{self.name} meows.”
This method speak in the Cat class overrides the speak method from Animal. The method returns a specific message where the cat meows, using the name of the instance.
The self.name is used to include the cat’s name in the output.
my_dog = Dog(“Buddy”)
An instance of the Dog class is created, and the name “Buddy” is passed as an argument to the constructor __init__.
The name attribute for my_dog is set to “Buddy”, and this instance will use the speak method from the Dog class, which returns a barking message.
my_cat = Cat(“Whiskers”)
Similarly, an instance of the Cat class is created with the name “Whiskers”.
This instance will use the speak method from the Cat class, which returns a meowing message.
Output:
Buddy barks.
Whiskers meows.
● Multiple Inheritance: Multiple-level inheritance enables one derived class to inherit properties from more than one base class.
Example:
# Base class 1
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f”{self.name} makes a sound.”
# Base class 2
class Vehicle:
def __init__(self, speed):
self.speed = speed
def drive(self):
return f”Driving at {self.speed} mph.”
# Derived class (inherits from both Animal and Vehicle)
class DogCar(Animal, Vehicle):
def __init__(self, name, speed):
Animal.__init__(self, name)
Vehicle.__init__(self, speed)
def show_ability(self):
return f”{self.name} can drive at {self.speed} mph.”
# Creating an instance of the derived class
dog_car = DogCar(“Rover”, 30)
print(dog_car.speak())) # Output: Rover makes a sound.
print(dog_car.drive()) ) # Output: Driving at 30 mph.
print(dog_car.show_ability()) # Output: Rover can drive at 30 mph.
Explanation:
class Animal:
This defines the first base class Animal.
def __init__(self, name):
self.name = name
The constructor __init__ is used to initialize a Vehicle object with a speed attribute. The speed represents how fast the vehicle can go.
def drive(self):
return f”Driving at {self.speed} mph.”
The drive method returns a message indicating the vehicle’s speed using the speed attribute.
class DogCar(Animal, Vehicle):
This defines a derived class DogCar that inherits from both Animal and Vehicle classes. This is an example of multiple inheritance.
def __init__(self, name, speed):
Animal.__init__(self, name)
Vehicle.__init__(self, speed)
The constructor __init__ of the DogCar class accepts two parameters: name and speed.
Inside this constructor, it explicitly calls the constructors of both parent classes (Animal and Vehicle) to initialize the respective attributes (name and speed).
Animal.__init__(self, name) initializes the name attribute.
Vehicle.__init__(self, speed) initializes the speed attribute.
def show_ability(self):
return f”{self.name} can drive at {self.speed} mph.”
The show_ability method returns a message that combines the animal’s name and its ability to drive at a certain speed, using both the name and speed attributes inherited from the Animal and Vehicle classes.
dog_car = DogCar(“Rover”, 30)
This line creates an instance of the DogCar class called dog_car.
The parameters “Rover” and 30 are passed to the __init__ method, where:
name = “Rover” and initializes the name attribute using the Animal class constructor.
speed = 30 and initializes the speed attribute using the Vehicle class constructor.
print(dog_car.speak()) # Output: Rover makes a sound.
The speak method is called on the dog_car instance. Since DogCar inherits from Animal, it uses the speak method from the Animal class.
print(dog_car.drive()) # Output: Driving at 30 mph.
The drive method is called on the dog_car instance. Since DogCar inherits from Vehicle, it uses the drive method from the Vehicle class.
print(dog_car.show_ability()) # Output: Rover can drive at 30 mph.
Course Video
Course Video English:
Task
1. Single Inheritance:
Create a base class Vehicle with a method Start that prints “Vehicle started”. Derive a class Car from Vehicle and add a method Drive that prints “Car is driving”. Create an object of Car in the Main method, call the Start and Drive methods.
2. Hierarchical Inheritance:
Create a base class Person with a method Walk that prints “Person is walking”. Derive two classes Student and Teacher from Person. Add a method Study in Student that prints “Student is studying” and a method Teach in Teacher that prints “Teacher is teaching”. Create objects of Student and Teacher in the Main method and call their respective methods.
3. Multilevel Inheritance:
Create a base class ElectronicDevice with a method TurnOn that prints “Device turned on”. Derive a class Computer from ElectronicDevice and add a method Boot that prints “Computer is booting”. Further derive a class Laptop from Computer and add a method Charge that prints “Laptop is charging”. Create an object of Laptop in the Main method, call all methods.
Task Video
YouTube Reference :
It allows a class to inherit attributes and methods from another class.
In OOP, inheritance enables a class to derive properties and behaviors from another class.
Types include single, multiple, multilevel, hierarchical, and hybrid inheritance.
Achieved by passing a parent class to the child class.
Correct Syntax: class ChildClass(ParentClass):
class Dog(Animal): where Dog inherits Animal’s methods.
Use issubclass() or check __bases__.
Check Inherited Class: Use issubclass() to check.
Test Inequality: Use !=.
Non-supported Inheritance: Multiple inheritance with diamond problem isn’t directly supported.