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.selfis 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: Writingusername = usernamecreates a local variable instead of an instance attribute. Always useself.attribute = value. - Passing
selfexplicitly: CallingUser(self, "name")causes an error. Python passesselfautomatically. - Returning a value:
__init__must returnNone. Returning anything else raises aTypeError. - Missing arguments: If
__init__expects two arguments but you provide one, Python raises aTypeError. 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.