Module 4 Lesson 3: The __init__ Method
Master the constructor. Learn how to use the special __init__ method and the 'self' keyword to initialize objects with data.
Module 4 Lesson 3: The __init__ Method
In the last lesson, we created objects and manually added attributes like dog.name = "Buddy". This is fine for one object, but if you have 10,000 objects, it’s impossible. Python solves this with a special "Constructor" method called __init__.
Lesson Overview
In this lesson, we will cover:
- The Constructor: What
__init__does. - The
selfKeyword: Connecting data to a specific object. - Parameters in Classes: Passing data during creation.
- Real-world Example: Building a more efficient
Userclass.
1. What is __init__?
The name __init__ is short for initialize. It is a special function that runs automatically the moment you create a new object from a class. Think of it as the "birth" of the object where its basic traits are determined.
2. Meet the self Keyword
Inside a class, we use self to refer to the current object being worked on. It’s like the object saying, "Hey Python, this is my name, not some other dog’s name."
class Dog:
def __init__(self, name, breed):
self.name = name # Store the input 'name' into the object's trait
self.breed = breed # Store the input 'breed' into the object's trait
# Now we pass the data inside the parentheses!
my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Max", "Husky")
print(my_dog.name) # Output: Buddy
print(your_dog.name) # Output: Max
3. How it Works (Under the Hood)
When you run my_dog = Dog("Buddy", "Golden Retriever"):
- Python creates an empty object in memory.
- Python automatically calls
__init__. - The word
selfbecomes a label for that new empty object. - The data ("Buddy", "Golden Retriever") is assigned to the
selflabels (self.name,self.breed). - The finished object is returned to the variable
my_dog.
4. Default Values in __init__
Just like normal functions, you can have default values in your constructors.
class User:
def __init__(self, username, role="Member"):
self.username = username
self.role = role
admin = User("MasterDev", "Admin")
guest = User("Anonymous") # role defaults to "Member"
Practice Exercise: The Smartphone Maker
Create a file named smartphones.py.
- Define a class
Phone. - Add an
__init__method that takesbrand,model, andstorage. - Inside
__init__, also create an attributebattery_levelthat always starts at100(does not need to be a parameter!). - Create two phone objects with different brands and models.
- Print out their details and their initial battery levels.
Quick Knowledge Check
- What does
__init__stand for? - When does the
__init__method run? - In your own words, what does the
selfkeyword represent? - True or False: You have to manually call
my_object.__init__()to make it work.
Key Takeaways
__init__is the constructor method in Python.- It is used to set initial data (attributes) for your objects.
selfis a reference to the current instance of the class.- Data passed during instantiation goes directly into the
__init__parameters.
What’s Next?
We know how to store data in objects. Now let's learn how to make them do something! In Lesson 4, we’ll explore Instance Methods—functions that belong specifically to an object!