,

Python Inheritance – Understand in Depth

Inheritance is like passing down traits from parents to children. It lets one class inherit all the features (methods and properties) of another class.

The “parent class” is the original class that is being inherited from, kind of like the family tree’s ancestor.

The “child class” is the new class that inherits from the parent class, like the next generation inheriting traits from their ancestors.

Let us create a parent class –

Remember

Any class can be a parent class, so the syntax is the same as creating any other class:

Here, we will create a class named Person, with firstname and lastname properties, and a printname method:

class Person:
  def __init__(self, fname, lname):
    self.firstname = fname
    self.lastname = lname

  def printname(self):
    print(self.firstname, self.lastname)

#Use the Person class to create an object, and then execute the printname method:

x = Person("Ram", "Shyam")
x.printname()

Output:

Explanation of the above code:

Imagine we have a blueprint for creating people called “Person.” This blueprint has instructions on how to create a person’s first name and last name.

When we use this blueprint to create a person named “x” with the first name “Ram” and last name “Shyam,” we follow the instructions in the blueprint.

Then, when we tell “x” to execute the “printname” method, it follows another set of instructions in the blueprint that tells it to print out its first name and last name.

So, in simpler terms, this code creates a person named “Ram Shyam” and then tells that person to print out their name.

Now, let us understand how to create a child class

In programming, a child class is like a new class that’s based on an existing class.

Imagine you have a class called “Person” that defines basic properties like first name and last name.

Now, let’s say you want to create a more specific class for “Student.”

Instead of starting from scratch, you can create a “Student” class that inherits all the properties and behaviors of the “Person” class.

This way, you don’t have to redefine everything for a student; you can just add or modify what’s unique to student.

Create a class named Student, which will inherit the properties and methods from the Person class:

class Student(Person):
  pass

Now the Student class has the same properties and methods as the Person class.

let us use the Student class to create an object, and then execute the printname method:

x = Student("Mike", "Richard")
x.printname()

Note: Use the pass keyword when you do not want to add any other properties or methods to the class.

–init()–Function in Inheritance

In the above example of a “Person” class as the parent and a “Student” class as the child, the init() function is a special method used in Python classes to initialize objects.

In the parent class “Person,” the init() function might define attributes like name and age.

When we create a child class “Student” that inherits from “Person,” the init() function in the child class can use the super() function to call the init() method of the parent class and then add its own unique attributes like student_id.

So, in simple terms, the init() function helps set up initial values for objects, and in inheritance, it allows child classes to inherit and extend the initialization process from parent classes.

Add the init() function to the Student class:

class Student(Person):
  def __init__(self, fname, lname):
    #add properties etc.
class Student(Person):
  def __init__(self, fname, lname):
    Person.__init__(self, fname, lname)

Now we have successfully added the init() function, and kept the inheritance of the parent class, and we are ready to add functionality in the init() function.

Python also has a super() function that will make the child class inherit all the methods and properties from its parent:

class Student(Person):
  def __init__(self, fname, lname):
    super().__init__(fname, lname)

In this by using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.

Summary of Init() and Super() Function

When you use inheritance, you might want the child class to inherit and extend the initialization process of the parent class. That’s where the super() function comes in. It allows you to call the init() method of the parent class from within the child class. This way, you can reuse the initialization code from the parent class and then add or modify it in the child class.

So, in simple terms, init() is used to set up object attributes, and super() is used to extend and reuse initialization code from parent classes in child classes.

Let us say, you want to add a property to your class. Here in the below code graduationyear is the property for the class student.

class Student(Person):
  def __init__(self, fname, lname):
    super().__init__(fname, lname)
    self.graduationyear = 2019
class Student(Person):
  def __init__(self, fname, lname, year):
    super().__init__(fname, lname)
    self.graduationyear = year

x = Student("Mike", "Richard", 2019)

How to add Method ?

let us add a method welcome() to the class student

class Student(Person):
  def __init__(self, fname, lname, year):
    super().__init__(fname, lname)
    self.graduationyear = year

  def welcome(self):
    print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.

Examples for you to practice

Single Inheritance:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        pass

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

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak())  # Output: Buddy says Woof!
print(cat.speak())  # Output: Whiskers says Meow!

Multiple Inheritance:

class A:
    def explore(self):
        return "Explore A"

class B:
    def search(self):
        return "Search B"

class C(A, B):
    def discover(self):
        return "Discover C"

obj = C()
print(obj.explore())   # Output: Explore A
print(obj.search())    # Output: Search B
print(obj.discover())  # Output: Discover C

Method Overriding:

class Shape:
    def area(self):
        return 0

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

square = Square(5)
print("Area of square:", square.area())  # Output: Area of square: 25

Super() Function:

class A:
    def __init__(self):
        print("Init of A")

class B(A):
    def __init__(self):
        super().__init__()
        print("Init of B")

obj = B()
# Output: 
# Init of A
# Init of B

Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>