Initialize new instances with the __init__() method.
How It Works
__init__(self, ...) runs after an instance has been created and usually assigns its initial attributes. It must not return a non-None value. It is an initializer, not the allocator that constructs the instance.
Use __post_init__() in dataclasses for post-generated-initializer validation.
Step-by-Step Example
class Subscription:
def __init__(self, user_name, active=True):
self.user_name = user_name
self.active = active
subscription = Subscription("Morgan")
print(subscription.user_name, subscription.active)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Morgan True
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Add an optional renewal date field to a small class.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Returning a value from __init__() rather than setting instance state.
- Forgetting to define all attributes that other instance methods expect later.
Key Takeaways
- Initialize new instances with the __init__() method.
- __init__(self, ...) runs after an instance has been created and usually assigns its initial attributes.
- Use __post_init__() in dataclasses for post-generated-initializer validation.