The __init__ Constructor
The init Constructor
So far, you created objects first, then added attributes later.
tom = Student()
tom.name = "Tom"
tom.score = 85
There is a better way.
Python gives us __init__() to set up objects when they are created.
What Is init()?
__init__() is a special method called automatically when you create an object.
It is used to give starting values to attributes.
Why It Matters
It helps you:
- create objects faster
- avoid missing attributes
- keep code cleaner
- give every object a clear starting state
Basic Structure
class ClassName:
def __init__(self, value):
self.attribute = value
First Example
class Student:
def __init__(self, name):
self.name = name
tom = Student("Tom")
print(tom.name)
Output
Tom
Two Attributes
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
sara = Student("Sara", 92)
print(sara.name)
print(sara.score)
Output
Sara
92
How It Works
When you run:
sara = Student("Sara", 92)
Python automatically runs:
__init__(self, "Sara", 92)
and saves the values.
Add Other Methods Too
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def show_info(self):
print(self.name, self.score)
tom = Student("Tom", 85)
tom.show_info()
Output
Tom 85
Multiple Objects
tom = Student("Tom", 85)
sara = Student("Sara", 92)
print(tom.name)
print(sara.name)
Output
Tom
Sara
Common Beginner Errors
Forgetting self
def __init__(name):
Wrong.
Use:
def __init__(self, name):
Wrong Number of Values
If __init__() expects two values, give two values.
Code Along
Create a class called Book.
Use __init__() with:
- title
- price
Create one book and print both values.
Mini Challenge
Create a class called Phone.
Steps:
-
Use
__init__()with:- brand
- model
- price
-
Create:
phone1 = Phone("Apple", "iPhone", 999)
- Print all values
Expected output:
Apple
iPhone
999
Real World Use Case
Apps use constructors to create users, products, orders, bank accounts, and game characters with starting data.
Quiz
- What is
__init__()? - When does it run?
- Why is it useful?
- Can a class have other methods too?
Assignment
Create a class called Car with brand and color using __init__().
Summary
You learned how __init__() gives objects starting values when they are created.