Back to Python Notes
Topic #234

The __init__ Method

By the end of this lesson, you will understand how to use the __init__ method to initialize attributes when creating new instances of a Python class.

What it is

The __init__ method is a special instance method in Python classes. It acts as an initializer (often mistakenly called a constructor) that runs automatically whenever a new object is created from the class. Its primary purpose is to set up the initial state of the object by assigning values to its attributes.

Mental Model: Think of __init__ as the "setup phase" for a blueprint. When you build a house (create an object), __init__ ensures the foundation, walls, and roof are placed correctly before anyone moves in.

Related terms include instance (the specific object created), attribute (data stored on the object), and self (a reference to the current instance).

Why it matters

  • Data Encapsulation: It allows each object to hold its own unique data securely.
  • Consistency: Ensures every instance starts with required attributes, preventing errors later.
  • Readability: Clearly defines what data an object needs to function properly.
  • Reusability: You can create multiple objects with different configurations using the same class definition.

Syntax or steps

The basic syntax requires defining the method inside a class. The first parameter must always be self, which refers to the instance being created. Additional parameters define the data needed to initialize the object.

class ClassName:
    def __init__(self, param1, param2):
        self.attribute1 = param1
        self.attribute2 = param2

Example

Here is a realistic example of a User class that initializes a username and email address.

class User:
    def __init__(self, username, email):
        self.username = username
        self.email = email
        self.is_active = True  # Default value

# Creating an instance
new_user = User("alice_dev", "alice@example.com")

print(new_user.username)   # Output: alice_dev
print(new_user.email)      # Output: alice@example.com
print(new_user.is_active)  # Output: True

Part-by-part explanation:

  • class User: Defines the blueprint.
  • def __init__(self, username, email): Sets up the initializer. self is implicit; you do not pass it when calling the class.
  • self.username = username: Assigns the passed argument to the instance's attribute.
  • self.is_active = True: Sets a default attribute without requiring an external argument.
  • new_user = User(...): Calls the class, triggering __init__ and returning the new object.

Common mistakes

  • Forgetting self: Writing username = username creates a local variable instead of an instance attribute. Always use self.attribute = value.
  • Passing self explicitly: Calling User(self, "name") causes an error. Python passes self automatically.
  • Returning a value: __init__ must return None. Returning anything else raises a TypeError.
  • Missing arguments: If __init__ expects two arguments but you provide one, Python raises a TypeError. Use default parameters if some are optional.

When to use it

Use __init__ for setting up instance-specific data. Compare it with other methods below:

Method Purpose When to Use
__init__ Initialize instance attributes Every time a new object is created
__new__ Create the instance itself Rarely; only for immutable types or singletons
Regular Methods Perform actions on existing data After the object is fully initialized

Practice

Guided Exercise: Create a Rectangle class with width and height attributes. Initialize them in __init__.

Challenge: Add a default value of 10 for both width and height if no arguments are provided during instantiation.

Solution Hint: Use default parameters in the function signature: def __init__(self, width=10, height=10):.

Quick check

Question: Why is self required as the first parameter in __init__?

Answer: self refers to the specific instance being created, allowing the method to assign attributes to that particular object rather than the class itself.

Summary

The __init__ method is essential for defining the initial state of Python objects. By correctly using self to bind attributes, you ensure that each instance maintains its own unique data, forming the backbone of object-oriented programming in Python.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

The __init__ Method – FAQs

Quick answers about learning The __init__ Method in Python.

This free note from Coding Now Tech Institute explains The __init__ Method in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including The __init__ Method, is 100% free with no signup required.
With focused practice, most students grasp The __init__ Method in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now