How To Use Inheritance in Python (2024)

In object-oriented programming, there’s a feature called inheritance that allows a new class to inherit the attributes and methods of an existing class. By using inheritance, you don’t have to always reinvent the wheel, which also means your code will be more concise and easier to read and debug.

First, what is a class?

Think of a class as a blueprint for creating objects, and also for defining the properties (attributes) and behaviors (methods) that will be associated with the objects created from the class. A class is like a template you can use and reuse within your code.

Inheritance requires two types of classes:

  • Base class (aka parent class): This is the class whose attributes and methods will be inherited.
  • Derived class (aka child class): This is the class that inherits the attributes and methods.

There are five types of inheritance:

  • Single inheritance: A derived class inherits from a single base class.
  • Multiple inheritance: A derived class inherits from multiple base classes.
  • Multilevel inheritance: A class is derived from a class, which is derived from another class.
  • Hierarchical inheritance: Multiple classes are derived from a single base class.
  • Hybrid inheritance: A combination of two or more types of inheritance.

The benefits of using inheritance include:

  • Code reusability
  • Extensibility
  • Better code organization

The basic syntax of class inheritance looks like this:

1

2

3

4

5

class baseClass:

# Base class attributes and methods

class derivedClass(baseClass)

# Derived class attributes and methods


Let’s first create a base class. This will make use of several concepts I’ve outlined throughout this Python series.

We’ll create a base class that defines a person’s name and looks like this:

1

2

3

4

5

6

7

class Person:

def __init__(fullName, fname, lname):

fullName.firstname = fname

fullName.lastname = lname

def printname(fullName):

print(fullName.firstname, fullName.lastname)


Now that we’ve created our class, we then use it to create an object and print the object like so:

1

2

x = Person("Jack", "Wallen")

x.printname()


Put all of that together and it looks like this:

1

2

3

4

5

6

7

8

9

10

class Person:

def __init__(fullName, fname, lname):

fullName.firstname = fname

fullName.lastname = lname

def printname(fullName):

print(fullName.firstname, fullName.lastname)

x = Person("Jack", "Wallen")

x.printname()


Run the above command and it will print “Jack Wallen”.

That’s the base class. We’ve create a derived class that inherits the attributes and methods from the base class (Person). This is the easy part. We’ll create a new class, named Staff, which inherits from Person. The class looks like this:

1

2

class Staff(Person)

pass


By using pass, we inform Python that we’re not adding any new attributes or methods to the new class.

We can then create a new object from the derived class like so:

1

x = Staff("Olivia", "Nightingale")


Print the new object with:

1

x.printname()


The entire code now looks like this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

class Person:

def __init__(fullName, fname, lname):

fullName.firstname = fname

fullName.lastname = lname

def printname(fullName):

print(fullName.firstname, fullName.lastname)

x = Person("Jack", "Wallen")

x.printname()

class Staff(Person):

pass

x = Staff("Olivia", "Nightingale")

x.printname()


Run the above code and it will print:

Jack Wallen
Olivia Nightingale

Remember that we previously used pass because we didn’t want to add any new attributes or methods to the new class. Now, we’re going to add new attributes and methods to a new class. We’ll stick with something similar to our original — our base class. This time around the base class is:

1

2

3

4

5

6

7

8

9

10

class Person(object):

def __init__(fullName, name):

fullName.name = name

def getName(fullName):

return fullName.name

def isEmployee(fullName):

return False


We’ve added two new functions above, getName (to return the full name of the person) and isEmployee (assuming isEmployee equals false).

Next, we’ll create a derived class to define that isEmployee equals True, which looks like this:

1

2

3

4

class Employee(Person):

def isEmployee(fullName):

return True


So far, we have a class called Person and one called Employee. As you might assume, Person is not an employee, whereas Employee is. You’ll see that in action below with:

1

2

3

4

5

emp = Person("Jack Wallen")

print(emp.getName(), emp.isEmployee())

emp = Employee("Olivia Nightingale")

print(emp.getName(), emp.isEmployee())


You should be able to guess what’s going to happen. Since Jack Wallen is an object of the Person class, they’ll not be listed as an employee, whereas Olivia Nightingale, who is an object of the Employee class, is.

The entire code looks like this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

class Person(object):

def __init__(fullName, name):

fullName.name = name

def getName(fullName):

return fullName.name

def isEmployee(fullName):

return False

class Employee(Person):

def isEmployee(fullName):

return True

emp = Person("Jack Wallen")

print(emp.getName(), emp.isEmployee())

emp = Employee("Olivia Nightingale")

print(emp.getName(), emp.isEmployee())


Run the above and the output will be:

Jack Wallen False
Olivia Nightingale True

Pretty nifty, eh?

Using the super() Function

There’s also the super() function, which forces the derived class to inherit all attributes and methods from the base class. This time around, we’re going to focus on students and their graduation year.

The super() function is used like this:

1

2

3

4

class Student(Person):

def __init__(fullName, fname, lname, year):

super().__init__(fname, lname)

fullName.graduationyear = year


The explanation of the super() function (in the above example) is:

  • super(): Returns a temporary object of the superclass that allows the calling of its methods
  • __init__(): The Python constructor method used for initializing new objects
  • (fname, lname): Parameters passed to the superclass constructor

Our entire code looks like this:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

class Person:

def __init__(fullName, fname, lname):

fullName.firstname = fname

fullName.lastname = lname

def printname(fullName):

print(fullName.firstname, fullName.lastname)

class Student(Person):

def __init__(fullName, fname, lname, year):

super().__init__(fname, lname)

fullName.graduationyear = year

def welcome(fullName):

print("Welcome", fullName.firstname, fullName.lastname, "to the class of", fullName.graduationyear)

x = Student("Jack", "Wallen", 2026)

x.welcome()


Run the above code and the output would be:

Welcome Jack Wallen to the class of 2026

And that’s the basics of Python inheritance. To learn more about inheritance, check out the official Python documentation on the subject.

TRENDING STORIES

Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides... Read more from Jack Wallen
How To Use Inheritance in Python (2024)

FAQs

How is inheritance used in Python? ›

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

What are the limitations of inheritance in Python? ›

The disadvantages of inheritance in Python are: a) Since classes are inherited from one class to another, they are interdependent. This means that the execution speed of running the code decreases. b) Child classes cannot be executed independently without defining the parent class in the code.

Why not use inheritance in Python? ›

Tight Coupling: Inheritance binds the child class to its parent, often leading to a rigid structure that's hard to break. This makes the system less flexible and more susceptible to bugs during extension or modification.

What does super() do in Python? ›

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.

What is an example of inheritance? ›

Inheritance is a technique of modelling real-world relationships, and OOP is all about real-world objects. Here's an example: a car, a bus, and a bicycle all fall under the umbrella term "vehicle." That is, they have inherited the attributes of the vehicle class, implying that they are all utilised for transportation.

How do you use inheritance in programming? ›

Declare an inheritance hierarchy

That class is called a superclass, or parent class. The derived class is called subclass, or child class. You use the keyword extends to identify the class that your subclass extends. If you don't declare a superclass, your class implicitly extends the class Object.

What is the main advantage of using inheritance in Python? ›

Advantages of Inheritance in Python

Code Reusability: the child class copies all the attributes and methods of the parent class into its class and use. It saves time and coding effort by not rewriting them, thus following modularity paradigms.

What is the main disadvantage of inheritance? ›

Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other.

Is multiple inheritance good or bad in Python? ›

Multiple inheritance solves certain kinds of problems, but it can also make code rather difficult to follow along.

What is a major problem with inheritance? ›

One of the most common issues with inheritance is the dispute over assets. When an estate's value is high, and multiple beneficiaries are involved, this can cause problems. Disputes arise when individuals claim ownership over assets that another individual feels entitled to.

When should inheritance not be used? ›

Inheritance is not useful in every scenario. For instance, extending the class Car with the class Part (or Engine ) would be incorrect. A car includes an engine and parts, but an engine or a part is not a car. More generally, if an object owns or is composed of other objects, inheritance should not be used.

Why avoid inheritance? ›

To summarize, while inheritance is a powerful tool in OOP, it can lead to problems like tight coupling between classes. By avoiding inheritance and using alternatives like interfaces and delegates, you can write code that is easier to maintain, debug, and test, and that is more flexible and reusable.

Is super __ init __ called automatically in Python? ›

__init__() of the superclass ( Square ) will be called automatically. super() returns a delegate object to a parent class, so you call the method you want directly on it: super(). area() . Not only does this save us from having to rewrite the area calculations, but it also allows us to change the internal .

Does Python support multiple inheritance? ›

Yes, a class can inherit from more than two parent classes in Python. There is no hard limit on the number of parent classes a child class can inherit from.

Do I need to call super init? ›

If all you want to do is have your subclass call the init method of your superclass, you don't have to use super at all! Only if you overwrite the init method in Second, but still want to execute the init method of Second's superclass, you need to use super.

How is inheritance useful in programming terms? ›

Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors (realizing an interface), to reuse code and to independently extend original software via public classes and interfaces.

When should you use class inheritance? ›

In general, Inheritance is useful when there is a clear hierarchy or a "is-a" relationship between classes, while Composition is useful when there is a "has-a" relationship between classes.

Why do we inherit object class in Python? ›

In Python, every class implicitly inherits from the object class, which is the root of the class hierarchy. This is because Python follows the object-oriented programming paradigm, where everything is an object, and all objects have properties and methods that define their behavior.

How do you use inheritance and Polymorphism in Python? ›

How to achieve polymorphism using class inheritance? Polymorphism can be achieved using class inheritance by defining a common interface in a base class and then providing specific implementations in derived classes. This allows objects of different classes to be treated as objects of a common superclass.

Top Articles
Evil act of mass murder at Bangkok tea party of death in the heart of the capital shocks Thailand and the World - Thai Examiner
Jon Voight on Being Hollywood’s Most Outspoken Trump Supporter and Fighting Angelina Jolie Over Israel-Palestine: ‘She’s Been Influenced by Antisemitic People’
Gortershof in Zaandijk | AlleCijfers.nl
Https Paperlesspay Talx Com Boydgaming
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Mensenlinq: Overlijdensberichten zoeken in 2024
Sigma Aldrich Calculator
The Blind Showtimes Near Merchants Walk Cinemas
Public Agent.502
2014 Can-Am Spyder ST-S
Fkiqx Breakpoints
Lakeport Craigslist
2013 Chevy Sonic Freon Capacity
R/Skinwalker
Las Mejores Tiendas Online en Estados Unidos - Aerobox Argentina
Rocky Bfb Asset
Dcuo Exalted Style
라이키 유출
Restaurant Depot Flyer December 2022
Lighthouse Diner Taylorsville Menu
Laura Houston Wbap
M&T Home Equity Loan Calculator
Www.publicsurplus.com Motor Pool
Beachbodyondemand.com
Los Garroberros Menu
Cric7.Net Ipl 2023
افضل موقع سكسي عربي
Marukai Honolulu Weekly Ads
The Civil Rights Movement Crossword Review Answer Key
Mike Temara
Otter Bustr
Age Of Attila's Rain Crossword
Odu Csnbbs
Miracle Child Brandon Lake Chords
The Untold Truth Of 'Counting Cars' Star - Danny Koker
Projo Sports High School
Lol Shot Io Unblocked
NO CLUE: deutsche Übersetzung von NCT 127
10.4: The Ideal Gas Equation
Amazing Lash Bay Colony
Racial Slur Database
Lowlifesymptoms Twitter
Blow Dry Bar Boynton Beach
Netdania.com Gold
Summer Rae on WWE return: Royal Rumble is 'step in the right direction'
Noel Berry's Biography: Age, Height, Boyfriend, Family, Net Worth
Roselli's Pizza Coupons
Circle K Wikipedia
Craigslist Old Forge
Eugenics Apush
Potion To Reset Attributes Conan
Enchiladas Suizas | Mexican Food Recipes, Quick and Easy.
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 6028

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.