Lesson 2: Inheritance

In this lesson, we will explore Inheritance, a key concept in Object-Oriented Programming (OOP) that allows one class to inherit attributes and methods from another. Inheritance promotes code reusability and helps in creating a hierarchical relationship between classes. By understanding inheritance, you will be able to create more complex classes by extending existing ones and customizing them as needed.

By the end of this lesson, you will have a strong understanding of:

  • Base and derived classes
  • Method overriding
  • Method Resolution Order (MRO)

1. Base and Derived Classes

In Inheritance, we have two types of classes:

  • Base Class (Parent Class): This is the class that provides the common attributes and methods to be inherited.
  • Derived Class (Child Class): This is the class that inherits from the base class and can have additional features or can modify the inherited behavior.
Syntax:

To define a derived class, you specify the base class in parentheses when defining the new class.

python
class DerivedClassName(BaseClassName):

# Additional attributes or methods

 

Example:
python
# Base Class (Parent)

class Animal:

def __init__(self, name):

self.name = name

 

def speak(self):

print(f”{self.name} makes a sound”)

 

# Derived Class (Child)

class Dog(Animal):

def __init__(self, name, breed):

# Call the __init__ method of the base class

super().__init__(name)

self.breed = breed

 

def speak(self):

print(f”{self.name} barks”)

 

In this example:

  • Animalis the base class with an __init__() method and a speak()
  • Dogis the derived class that inherits from Animal. It has an additional attribute breed, and the speak() method is overridden.
Instantiating Objects:
python

# Creating an object of the derived class

dog1 = Dog(“Buddy”, “Golden Retriever”)

 

# Accessing inherited method

dog1.speak()  # Output: Buddy barks

 

  • The Dogclass inherits the __init__() and speak() methods from the Animal However, the speak() method is overridden in the Dog class.

2. Overriding Methods

Method overriding is a feature that allows a derived class to provide a specific implementation of a method that is already defined in its base class. When a derived class defines a method with the same name as the one in the base class, the method in the derived class overrides the one in the base class.

Example:
python
# Base Class (Parent)

class Animal:

def speak(self):

print(“Animal makes a sound”)

 

# Derived Class (Child)

class Dog(Animal):

def speak(self):

print(“Dog barks”)

 

class Cat(Animal):

def speak(self):

print(“Cat meows”)

 

In this example:

  • Both Dogand Cat override the speak() method of the Animal
Using the Overridden Methods:
python
# Creating objects of derived classes

dog1 = Dog()

cat1 = Cat()

 

# Calling the overridden methods

dog1.speak()  # Output: Dog barks

cat1.speak()  # Output: Cat meows

 

  • The Dogand Cat classes provide their own specific implementation of the speak() method, which overrides the base class’s speak()

3. The super() Function

The super() function is used to call a method from the base class inside the derived class. It allows you to call the constructor or any method of the base class, which is particularly useful when you want to extend the behavior of the base class without completely overriding it.

Example:
python
class Animal:

def __init__(self, name):

self.name = name

 

def speak(self):

print(f”{self.name} makes a sound”)

 

class Dog(Animal):

def __init__(self, name, breed):

# Using super() to call the __init__ method of Animal

super().__init__(name)

self.breed = breed

 

def speak(self):

print(f”{self.name} barks”)

 

  • The super().__init__(name)in the Dog class calls the __init__() method of the Animal class to initialize the name This prevents duplicating the __init__() method and promotes code reuse.

4. Method Resolution Order (MRO)

Method Resolution Order (MRO) defines the order in which methods are inherited in multiple inheritance scenarios. When a derived class inherits from multiple base classes, the MRO determines which method is called first.

  • Python uses an algorithm called C3 Linearizationto determine the method resolution order in the case of multiple inheritance.
  • The mro()method can be used to display the method resolution order of a class.
Example of MRO:
python
class A:

def speak(self):

print(“A speaks”)

 

class B(A):

def speak(self):

print(“B speaks”)

 

class C(A):

def speak(self):

print(“C speaks”)

 

class D(B, C):

pass

 

# Creating an object of class D

obj = D()

obj.speak()  # Output: B speaks

 

# Displaying the Method Resolution Order

print(D.mro())

 

  • In this example, Dinherits from both B and C, which in turn inherit from A. When speak() is called, Python uses the MRO to determine that the speak() method from B is called first, because B appears before C in the inheritance hierarchy.

The output of D.mro() will show the order in which Python looks for methods when searching for an attribute or method. The MRO is:

kotlin
[<class ‘__main__.D’>, <class ‘__main__.B’>, <class ‘__main__.C’>, <class ‘__main__.A’>, <class ‘object’>]

 

5. Multiple Inheritance

Multiple inheritance allows a class to inherit from more than one base class. This can be useful when a class needs to combine behavior from different sources.

Example of Multiple Inheritance:
python
class Animal:

def speak(self):

print(“Animal speaks”)

 

class Flying:

def fly(self):

print(“Flying in the sky”)

 

class Bird(Animal, Flying):

pass

 

# Creating an object of the Bird class

bird = Bird()

 

bird.speak()  # Output: Animal speaks

bird.fly()  # Output: Flying in the sky

 

  • In this example, the Birdclass inherits from both Animal and Flying. As a result, Bird objects have access to both the speak() method from Animal and the fly() method from Flying.

6. Conclusion

In this lesson, we have covered the following key concepts:

  • Base and Derived Classes: A base class is the class being inherited from, while the derived class is the class that inherits the properties and methods.
  • Overriding Methods: You can override methods in a derived class to provide specific behavior.
  • The super()Function: The super() function allows you to call methods from the base class to reuse code and extend functionality.
  • Method Resolution Order (MRO): In multiple inheritance, MRO determines the order in which methods are resolved.
  • Multiple Inheritance: A class can inherit from multiple classes, gaining the combined features of all base classes.

Inheritance is a powerful feature of Python’s object-oriented programming, enabling code reusability and a structured approach to modeling real-world entities. In the next lesson, we will explore more OOP concepts like Polymorphism and Encapsulation.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *