Inheritance In Python

Flask Tutorial

Introduction

There is no object-oriented programming language that would be qualified to take a gander at or use, on the off chance that it didn’t uphold inheritance. Inheritance was concocted in 1969 for Simula. Python upholds inheritance as well as multiple inheritances also. As a rule, inheritance is the component of getting new classes from existing ones. By doing this, we get a pecking order of classes. In many class-based OOP languages, an object made through inheritance (a “child object”) gains all, – however, there are exemptions in some programming languages, – of the properties and practices of the parent object. 

Inheritance permits software engineers to make classes that are based on existing classes, and this empowers a class made through inheritance to acquire the properties and techniques for the parent class. This implies that inheritance upholds code reusability. The methods or as a rule the product acquired by a subclass is viewed as reused in the subclass. The relationships of items or classes through inheritance lead to a coordinated graph. 

The class from which a class acquires is known as the parent or superclass. A class that acquires from a superclass is known as a subclass, likewise called heir class or child class. Superclasses are now and then called precursors also. There exist various hierarchical connections between classes. It’s like connections or orders that we know from reality. Ponder vehicles, for instance. Bicycles, vehicles, transports, and trucks are vehicles. Pick-ups, vans, sports vehicles, convertibles, and bequest vehicles are altogether vehicles and by being vehicles they are vehicles also. We could carry out a vehicle class in Python, which may have strategies like speed up and brake. Vehicles, Buses and Trucks, and Bikes can be carried out as subclasses that will acquire these techniques from vehicles.

Inheritance is the ability of one class to infer or acquire properties from another class. The advantages of inheritance are: 

  • It addresses true connections well. 
  • It gives the reusability of a code. There is no purpose in composing a similar code over and over again. Likewise, it permits us to add more elements to a class without changing it. 
  • It is transitive, which implies that assuming class B acquires from another class A, every one of the subclasses of B would naturally acquire from class A. 

A language element would not be deserving of the name “class” without supporting inheritance. The language structure for a determined class definition resembles this: 

class DerivedClassName(BaseClassName): 

<statement-1> 

<statement-N> 

The name BaseClassName should be characterized in an extension containing the determined class definition. Instead of a base class name, other subjective articulations are additionally permitted. This can be valuable, for instance, when the base class is characterized in another module: 

class DerivedClassName(modname.BaseClassName): 

Execution of a determined class definition continues equivalent to for a base class. At the point when the class object is developed, the base class is recalled. This is utilized for settling characteristic references: if a mentioned property isn’t found in the class, the inquiry continues to glance in the base class. This standard is applied recursively if the base class itself is gotten from another class. 

There’s nothing extraordinary with regards to the launch of derived classes: DerivedClassName() makes another occurrence of the class. Method references are settled as follows: 

  • the relating class characteristic is looked at, 
  • slipping down the chain of base classes if fundamental, and 
  • the strategy reference is legitimate if this yields a capacity object. 

Derived classes might override strategies for their base classes. Since methods have no exceptional advantages when calling different strategies for a similar object, a method for a base class that calls one more method characterized in a similar base class might wind up considering a strategy for a determined class that abrogates it. (For C++ developers: all strategies in Python are adequately virtual.) 

An overriding method in a derived class may truth be told need to expand instead of essentially supplant the base class technique for a similar name. There is a basic method to call the base class method straightforwardly: simply call BaseClassName.method name(self, arguments)

This is every so often helpful to customers too. (Note that this possibly works if the base class is open as BaseClassName in the worldwide extension.) 

Python has two in-built functions that work with inheritance: 

  • Use instance() to take a look at an occasion’s sort: instance(obj, int) will be True just in case obj.__class__ is int or some class got from int. 
  • Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a subclass of int. Notwithstanding, issubclass(float, int) is False since the coast isn’t a subclass of int. 

Multiple Inheritance 

Python supports a type of multiple inheritance too. A class definition with various base classes resembles this: 

class DerivedClassName(Base1, Base2, Base3): 

<statement-1> 

<statement-N> 

For most purposes, in the most common causes, you can think about the quest for attributes acquired from a parent class as profundity first, left-to-right, not looking through twice in a similar class where there is a cross-over in the progressive system. In a similar way, when an attribute isn’t present in DerivedClassName, it looks for it in Base1, then, at that point (recursively) in the base classes of Base1, and in case it was not found there, it was looked for in Base2, etc. 

Indeed, it is somewhat more complicated than that; the strategy goal request changes powerfully to help agreeable calls to super(). This methodology is known in some other multiple inheritances languages as call-next-technique and is more impressive than the super call found in single-inheritance languages.

Dynamic ordering is vital because all instances of multiple inheritance display at least one precious diamond connection (where something like one of the parent classes can be gotten to through numerous ways from the bottommost class). For instance, all classes acquire from the object, so any instance of multiple inheritances gives more than one way to arrive at the object. To hold the base classes back from being gotten to more than once, the dynamic algorithm linearizes the inquiry request such that protects the left-to-right requesting indicated in each class, that calls each parent just a single time, and that is monotonic (implying that a class can be subclassed without influencing the priority request of its folks). Taken together, these properties make it conceivable to plan dependable and extensible classes with multiple inheritances.

In python, a derived class can acquire the base class simply by referencing the base in the section after the derived class name. Think about the accompanying language structure to acquire a base class into the derived class. 

Syntax:

class determined class(base class): 

<class-suite> 

A class can acquire different classes by referencing every one of them inside the section. Think about the accompanying language structure. 

Syntax:

class determine class(<base class 1>, <base class 2>, ….. <base class n>): 

<class – suite> 

Example 1 

class species: 

def speak(self): 

print(“way of speaking”) 

#child class Dog acquires the base class species 

class Dog(species): 

def bark(self): 

print(“dog woofing”) 

d = Dog() 

d.bark() 

d.speak() 

Output:

dog barking

way of speaking

Python Multi-Level inheritance

Multi-level Inheritance is conceivable in python like other OOP languages. Multi-level inheritance is filed when a derived class acquires one more derived class. There is no restriction on the number of levels up to which, the multi-level inheritance is filed in python. The syntax of multi-level inheritance is given below. 

Syntax:

class class1: 

<class-suite> 

class class2(class1): 

<class suite> 

class class3(class2): 

<class suite> 

.

Example

class species: 

def speak(self): 

print(“way of speaking”) 

#The child class Dog acquires the base class Animal 

class Dog(species): 

def bark(self): 

print(“dog woofing”) 

#The child class Dogchild acquires another child class Dog 

class DogChild(Dog): 

def eat(self): 

print(“Eating bread…”) 

d = DogChild() 

d.bark() 

d.speak() 

d.eat() 

Output:

dog barking

way of speaking

Eating bread…

Python Multiple inheritances

Python gives us the adaptability to acquire different base classes in the youngster class. The syntax to execute the program of multiple inheritances is given below:

class Base1: 

<class-suite> 

class Base2: 

<class-suite> 

class BaseN: 

<class-suite> 

class Derived(Base1, Base2, …… BaseN): 

<class-suite> 

Example:

class Calc1: 

def Summation(self,a,b): 

return a+b; 

class Calc2: 

def Multiplication(self,a,b): 

return a*b; 

class Derived(Calc1,Calc2): 

def Divide(self,a,b): 

return a/b; 

d = Derived() 

print(d.Summation(10,20)) 

print(d.Multiplication(10,20)) 

print(d.Divide(10,20)) 

Output:

30

200

0.5

The issubclass(sub,sup) method 

The issubclass(sub, sup) method is utilized to genuinely look at the connections between the predetermined classes. It returns True if the first class is the subclass of the second class, and False in any case. Let’s understand this with the example mentioned below.

class Calc2: 

def Summation(self,a,b): 

return a+b; 

class Calc3: 

def Multiplication(self,a,b): 

return a*b; 

class Derived(Calc2,Calc3): 

def Divide(self,a,b): 

return a/b; 

d = Derived() 

print(issubclass(Derived,Calc3)) 

print(issubclass(Calc2,Calc3)) 

Output:

True

False

The isinstance (obj, class) method 

The isinstance() method is utilized to genuinely take a look at the connection between the objects and classes. It returns True if the main parameter, i.e., obj is the occasion of the subsequent parameter, i.e., class. To understand better, let’s look at the following example given below:

class Calc1: 

def Summation(self,x,y): 

return x+y; 

class Calc2: 

def Multiplication(self,x,y): 

return x*y; 

class Derived(Calc1,Calc2): 

def Divide(self,x,y): 

return x/y; 

d = Derived() 

print(isinstance(d,Derived))

Output:

True

Hence, Inheritance permits us to characterize a class that acquires every one of the methods and properties from another class. The parent class is the class being acquired from, additionally called the base class. The child class is the class that acquires from another class, additionally called derived class.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top