In this lesson, you will learn how to go beyond basic variable assignment by embedding custom setup logic directly into the __init__ constructor.
When you create a new object, the __init__ method acts as a dedicated space for "getting things ready." While assigning values to attributes is the most common task, this method is also the perfect place to run code that must happen the moment an object comes to life—such as calculating starting values, establishing connections, or normalizing input data.
Beyond Simple Assignment
Consider a scenario where you are building a SavingsAccount class. Instead of just storing the starting balance, you might want to automatically apply a "welcome bonus" or ensure the account status is set based on the initial deposit.
class SavingsAccount:
def __init__(self, owner, initial_deposit):
self.owner = owner
# Custom logic: Add a $10 bonus if the deposit is over $100
if initial_deposit >= 100:
self.balance = initial_deposit + 10
self.status = "Premium"
else:
self.balance = initial_deposit
self.status = "Standard"
# Usage
my_account = SavingsAccount("Alice", 150)
print(my_account.balance) # Output: 160
print(my_account.status) # Output: Premium
Why Use Custom Logic in __init__?
By placing this logic inside __init__, you ensure that the object is "born" in a valid and fully configured state. If you waited until after the object was created to run these checks, you might accidentally use an uninitialized or incorrectly configured object elsewhere in your code.
By centralizing these "setup tasks," you make your object blueprints more robust and reliable. Whenever you instantiate an object, you can rest assured that your custom setup rules have already been executed, maintaining the integrity of your object's internal state from the very first line of code.
Key Takeaway: The __init__ method allows you to bundle data assignment with essential setup logic, ensuring every object starts its life fully configured and ready for use.