Using Multiple Constructors in Your Python Classes

Darren Jones
Darren Jones 13 Lessons 44m intermediate python

Sometimes you need to write a Python class that provides multiple ways to construct objects. In other words, you want a class that implements multiple constructors. This kind of class comes in handy when you need to create instances using different types or numbers of arguments. Having the tools to provide multiple constructors will help you write flexible classes that can adapt to changing needs.

Python offers several techniques and tools that you can use to construct classes, including simulating multiple constructors through optional arguments, customizing instance creation via class methods, and doing special dispatch with decorators. If you want to learn about these techniques and tools, then this video course is for you.

In this video course, you’ll learn how to:

  • Use optional arguments and type checking to simulate multiple constructors
  • Write multiple constructors using the built-in @classmethod decorator
  • Overload your class constructors using the @singledispatchmethod decorator

You’ll also get a peek under the hood at how Python internally constructs instances of a regular class and how some standard-library classes provide multiple constructors.

To get the most out of this video course, you should have basic knowledge of object-oriented programming and understand how to define class methods with @classmethod. You should also have experience working with decorators in Python.

What’s Included:

Downloadable Resources:

Related Learning Paths:

About Darren Jones

With 20 years as a teacher of music technology, Darren is keen to bring his skills to the Python table.

» More about Darren

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

← Browse All Courses