Python Constructor: A Beginner’s Guide to init

Have you ever created a Python class and found yourself repeatedly setting the same initial values for every object? You create a Book object, and then you have to manually set its titleauthor, and pages every single time. It’s repetitive, error-prone, and feels like there should be a better way.

What if you could set up your objects with their unique data right at the moment of creation? This is not only possible but a fundamental principle of clean, efficient object-oriented programming (OOP) in Python. The key to this is a special method called the constructor.

In this guide, you will learn what a Python constructor is, how to use the __init__ method, and how to effortlessly initialize your objects. By the end, you’ll be able to create robust and intuitive classes that set themselves up for success from the very start.

What is a Constructor in Python?

In simple terms, a constructor is a special method that automatically runs whenever you create a new instance of a class. Its primary job is to “construct” and initialize the new object.

Think of it like a factory assembly line. When you order a new car (create an object), the assembly line (the constructor) automatically installs the engine, seats, and wheels (initializes the attributes) so that the car is ready to go when it rolls off the line. You don’t get an empty shell of a car and then have to install everything manually.

In Python, this constructor method is always named __init__.

The __init__ Method: The Blueprint for Your Objects

The __init__ method is the heart of initializing new objects in Python. Let’s see the problem it solves with a simple class that doesn’t use a constructor.

class Book:
    # Without a constructor, we define default attributes.
    title = "Unknown"
    author = "Anonymous"
    pages = 100

# Creating objects
book1 = Book()
book2 = Book()

print(book1.title)  # Output: Unknown
print(book2.author) # Output: Anonymous

See the issue? Every book we create starts with the same, generic data. To customize them, we have to manually assign new values after creation, which is inefficient.

book1.title = "5.7"
book1.author = "Han"
book1.pages = 87

Let’s see how a constructor eliminates this multi-step process.

How to Create a Constructor with __init__

Creating a constructor is just like defining a function inside your class, but with a very specific name: __init__ (with double underscores on each side).

Here’s the basic syntax:

class MyClass:
    def __init__(self):
        # This code runs automatically when an object is created.
        print("An object was created!")

The self parameter is mandatory and refers to the instance of the class being created. It’s how the object refers to itself internally.

Let’s add this to our Book class.

class Book:
    def __init__(self):
        print("A book is being created!")

# The moment we create an object, __init__ runs.
book1 = Book()  # Output: A book is being created!
book2 = Book()  # Output: A book is being created!

This proves that the __init__ method is called automatically for each new object. But we’re still not initializing any unique data. Let’s fix that.

Initializing Instance Variables in the Constructor

The real power of the constructor is to initialize instance variables—the attributes that are unique to each object.

We do this by defining parameters in the __init__ method. When we create the object, we pass the values for these parameters, and the constructor uses them to set up the object.

Let’s refactor our Book class to use a proper constructor.

class Book:
    def __init__(self, title, author, pages):
        # Initialize instance variables using 'self'
        self.title = title
        self.author = author
        self.pages = pages
        print(f"Book '{title}' created!")

    def display_info(self):
        # Now we can use the instance variables initialized in __init__
        print(f"Author: {self.author}\nTitle: {self.title}\nPages: {self.pages}\n")

# Creating objects is now a one-step process!
book1 = Book("5.7", "Han", 87)
book2 = Book("A YouTube's Guide", "Dr. Al", 33)

book1.display_info()
book2.display_info()

Output:

Book '5.7' created!
Book 'A YouTube's Guide' created!
Author: Han
Title: 5.7
Pages: 87

Author: Dr. Al
Title: A YouTube's Guide
Pages: 33

Let’s break down what happens when book1 = Book("5.7", "Han", 87) is executed:

  1. The object book1 is created in memory.
  2. Python automatically calls Book.__init__().
  3. The self parameter is set to reference the new book1 object.
  4. The arguments "5.7""Han", and 87 are passed to the titleauthor, and pages parameters.
  5. Inside the constructor, self.title = title creates an attribute for book1 and sets it to "5.7". The same happens for author and pages.
  6. The object is now fully initialized and ready to use!

Common __init__ Pitfalls and How to Avoid Them

1. Forgetting self

This is the most common beginner mistake. Every method in a class, including __init__, must have self as its first parameter.

Incorrect:

def __init__(title, author, pages): # Error!

Correct:

def __init__(self, title, author, pages): # Correct!

2. Mismatched Number of Arguments

If your __init__ method expects three parameters besides self, you must provide three arguments when creating the object.

Incorrect:

book1 = Book("5.7") # TypeError! Missing 2 arguments.

Correct:

book1 = Book("5.7", "Han", 87) # Perfect.

Ready to Go from Basics to Pro?

Understanding constructors is a huge leap forward in your Python OOP journey, but it’s just the beginning. What about inheritance, polymorphism, decorators, or building complex, real-world applications? Trying to learn these advanced concepts through scattered tutorials can be frustrating and slow.

A structured course provides a clear path from beginner to proficient developer. With expert guidance, hands-on projects, and a supportive community, you can build a deep, practical understanding of Python that goes far beyond the basics. You’ll not only learn the “how” but also the “why,” enabling you to write clean, professional, and efficient code.

If you’re serious about mastering Python, check out our pre-recorded python comprehensive video course.

Conclusion

The Python constructor, the __init__ method, is your key to creating well-initialized and self-sufficient objects. It automates the setup process, making your code cleaner, more efficient, and easier to read. Remember, its core purpose is to initialize instance variables using the self keyword, and it runs automatically every time you create a new instance of a class.

Keep practicing by adding constructors to all your classes. Try creating classes for CarStudent, or BankAccount and see how much more powerful and intuitive your object-oriented code becomes!

Common Questions About Python Constructors

What’s the difference between __init__ and a constructor?
In many languages, a constructor is a separate concept. In Python, the __init__ method is the constructor. It’s the method responsible for initializing the new object. Technically, __new__ is the method that actually creates the instance, but __init__ is what we use 99% of the time for initialization.

Can a class have multiple __init__ methods?
No, Python does not support method overloading like some other languages. You cannot have multiple __init__ methods. However, you can achieve similar flexibility by using default parameters or optional arguments in a single __init__ method (e.g., def __init__(self, title="Unknown", author="Anonymous"):).

Is __init__ strictly necessary?
No. If your objects don’t need any initial data and can rely on default attributes set later, you don’t need an __init__ method. However, for most non-trivial classes, using __init__ is considered a best practice.