How to Use Constructors in Python?

In Python, you don’t have to manually set up every single detail of an object after you create it.

Instead, you use a special method called a Constructor to handle the heavy lifting automatically.

I’ve been developing in Python for over a decade, and I can tell you that mastering constructors is the moment you stop writing scripts and start building real applications.

In this tutorial, I will show you exactly how to use constructors in Python with examples you can actually use.

What is a Constructor in Python?

A constructor is a special type of method that Python calls automatically when you create a new instance of a class.

Its main job is to initialize the attributes (data) of that object so it’s ready to go immediately. In Python, the constructor is always named __init__.

Those double underscores are important; we call them “dunder” (double underscore) methods.

The Default Constructor (No Arguments)

Sometimes, you just want an object to start with some basic, standard settings. I use this often when I’m setting up a configuration object for a database connection or a web scraper.

Here is an example of a class that represents a standard office workstation in a US-based tech company.

class Workstation:
    # This is a default constructor
    def __init__(self):
        self.os = "Windows 11"
        self.status = "Available"
        self.location = "New York Office"

    def display_info(self):
        print(f"OS: {self.os}")
        print(f"Status: {self.status}")
        print(f"Location: {self.location}")

# Creating an object using the default constructor
my_desk = Workstation()
my_desk.display_info()

You can see the output in the screenshot below.

python constructor

In this case, every time I create a Workstation, it starts with “Windows 11” and “Available” by default.

It’s simple, clean, and prevents you from having “empty” objects floating around your code.

The Parameterized Constructor (With Arguments)

Most of the time, you’ll want your objects to be unique from the start.

This is where the parameterized constructor comes in. It allows you to pass specific data into the class when you create the object.

Think about a payroll system for a company in California. You wouldn’t want every employee to have the same name and salary!

class Employee:
    # This is a parameterized constructor
    def __init__(self, name, employee_id, salary):
        self.name = name
        self.employee_id = employee_id
        self.salary = salary

    def print_payroll(self):
        print(f"Employee: {self.name}")
        print(f"ID: {self.employee_id}")
        print(f"Monthly Salary: ${self.salary:,.2f}")

# Creating different objects with specific values
emp1 = Employee("Alice Smith", "USA-101", 8500)
emp2 = Employee("Bob Jones", "USA-102", 9200)

emp1.print_payroll()
emp2.print_payroll()

You can see the output in the screenshot below.

constructor in python

By passing name and salary directly into the constructor, I can create dozens of different employee objects in just a few lines of code.

Use Default Arguments in Constructors

I often find myself wanting the best of both worlds: flexibility and sensible defaults. Python allows you to set default values for your constructor parameters.

For instance, if most of your shipments are sent via “FedEx Ground” within the US, you can set that as a default, but still change it when needed.

class Shipment:
    # Constructor with a default argument
    def __init__(self, item_name, carrier="FedEx Ground"):
        self.item_name = item_name
        self.carrier = carrier

    def track(self):
        print(f"Shipping {self.item_name} via {self.carrier}")

# Uses the default carrier
package1 = Shipment("Laptop")
# Overrides the default carrier
package2 = Shipment("Monitor", "UPS Next Day Air")

package1.track()
package2.track()

You can see the output in the screenshot below.

python class constructor

This makes your classes much more “user-friendly” for other developers (or your future self).

The Difference Between __init__ and __new__

This is a question I get a lot from developers moving from Java or C++ to Python.

Technically, __new__ is the actual constructor because it creates the object instance in memory.

However, __init__ is the initializer that fills that object with data.

In 99% of your professional work, you will only ever need to use __init__.

You only touch __new__ if you are doing very advanced things like creating a “Singleton” (a class that can only have one instance).

Important Points to Remember

There are a few “unwritten rules” I’ve learned over the years that will save you hours of debugging:

  • The ‘self’ keyword: Always include self as the first argument in your constructor. It represents the specific object being created.
  • No Return Values: A constructor cannot return anything (except None). If you try to return a string or number, Python will throw a TypeError.
  • One Constructor Only: Python does not support multiple constructors as Java does. Use default arguments if you need different ways to initialize.

Constructors are the foundation of clean, professional Python code.

They ensure that your objects are always in a valid state the moment they are born.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.