
Python
Constructors are special methods that initialize objects when they are created. In Python, the constructor is the `__init__` method. It runs automatically when you create a new object and sets up the initial state with instance variables and default values.
A constructor is a method that runs automatically when you create an object. It initializes the object's attributes to starting values. The `__init__` method is Python's constructor. The name comes from "initialize"βit initializes the new object.
class Greeting:
def __init__(self, name):
self.name = name
print(f"Constructor called! Creating object for {name}")
def greet(self):
return f"Hello, {self.name}!"
# Creating an object automatically calls __init__
g = Greeting("Alice")
# Output: Constructor called! Creating object for Alice
print(g.greet())
# Output: Hello, Alice!The `__init__` method is where you initialize instance variables. The first parameter is always `self` (representing the object being created), followed by any parameters you want to accept when creating the object. These parameters let users provide data when creating an object.
class Person:
def __init__(self, name, age, email):
# Initialize instance variables
self.name = name
self.age = age
self.email = email
self.created_at = "2026-02-23" # You can set defaults
def introduce(self):
return f"{self.name}, {self.age} years old, {self.email}"
# Create objects with parameters
person1 = Person("Alice", 25, "alice@email.com")
person2 = Person("Bob", 30, "bob@email.com")
print(person1.introduce())
# Output: Alice, 25 years old, alice@email.comConstructor parameters allow users to customize objects when creating them. You can have any number of parameters (after `self`). These become instance variables or are used to calculate initial values.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
self.area = width * height # Calculate from parameters
def display(self):
return f"Rectangle: {self.width}x{self.height}, Area: {self.area}"
# Different objects with different dimensions
rect1 = Rectangle(5, 4)
rect2 = Rectangle(10, 3)
rect3 = Rectangle(7, 2)
print(rect1.display())
# Output: Rectangle: 5x4, Area: 20
print(rect2.display())
# Output: Rectangle: 10x3, Area: 30You can provide default values for constructor parameters. If a user doesn't provide a value, the default is used. This makes constructors more flexible.
class Animal:
def __init__(self, name, species="Unknown", age=0):
self.name = name
self.species = species
self.age = age
def get_info(self):
return f"{self.name} - {self.species}, Age: {self.age}"
# Create with all parameters
dog = Animal("Buddy", "Dog", 3)
print(dog.get_info())
# Output: Buddy - Dog, Age: 3
# Create with some defaults
cat = Animal("Whiskers", "Cat")
print(cat.get_info())
# Output: Whiskers - Cat, Age: 0
# Create with all defaults
mystery = Animal("Unknown")
print(mystery.get_info())
# Output: Unknown - Unknown, Age: 0Constructors can initialize complex data structures like lists and dictionaries. This allows objects to manage collections of data.
class Team:
def __init__(self, team_name):
self.team_name = team_name
self.members = [] # Initialize empty list
self.stats = {} # Initialize empty dict
self.wins = 0
def add_member(self, name):
self.members.append(name)
def set_stat(self, key, value):
self.stats[key] = value
def get_summary(self):
return f"{self.team_name}: {len(self.members)} members, {self.wins} wins"
team = Team("Eagles")
team.add_member("Alice")
team.add_member("Bob")
team.set_stat("points", 100)
team.wins = 5
print(team.get_summary())
# Output: Eagles: 2 members, 5 winsConstructors can validate input and raise errors if parameters are invalid. This ensures objects are created in a valid state.
class Account:
def __init__(self, username, password, initial_balance=0):
if not username or len(username) < 3:
raise ValueError("Username must be at least 3 characters")
if not password or len(password) < 6:
raise ValueError("Password must be at least 6 characters")
if initial_balance < 0:
raise ValueError("Initial balance cannot be negative")
self.username = username
self.password = password
self.balance = initial_balance
def get_info(self):
return f"Account: {self.username}, Balance: ${self.balance}"
# Valid account
acc1 = Account("alice", "password123", 1000)
print(acc1.get_info())
# Try invalid - this will raise an error
try:
acc2 = Account("ab", "short") # Invalid
except ValueError as e:
print(f"Error: {e}")class Book:
def __init__(self, title, author, isbn, year):
self.title = title
self.author = author
self.isbn = isbn
self.year = year
self.is_borrowed = False
self.borrowed_by = None
self.reviews = []
def borrow(self, borrower):
if not self.is_borrowed:
self.is_borrowed = True
self.borrowed_by = borrower
return f"Book '{self.title}' borrowed by {borrower}"
return f"Book is already borrowed by {self.borrowed_by}"
def return_book(self):
if self.is_borrowed:
self.is_borrowed = False
self.borrowed_by = None
return "Book returned"
return "Book was not borrowed"
def add_review(self, rating, comment):
self.reviews.append({"rating": rating, "comment": comment})
book = Book("1984", "George Orwell", "978-0-451-52493-2", 1949)
print(book.borrow("Alice"))
print(book.add_review(5, "Classic!"))
print(book.return_book())class Character:
def __init__(self, name, char_class, starting_level=1):
if starting_level < 1 or starting_level > 100:
raise ValueError("Level must be between 1 and 100")
self.name = name
self.char_class = char_class
self.level = starting_level
self.experience = 0
self.health = 100
self.mana = 50
self.inventory = []
self.abilities = self._initialize_abilities()
def _initialize_abilities(self):
# Private method to set up starting abilities
if self.char_class == "Warrior":
return ["Slash", "Block"]
elif self.char_class == "Mage":
return ["Fireball", "Shield"]
else:
return ["Attack"]
def gain_experience(self, amount):
self.experience += amount
def get_status(self):
return f"{self.name} ({self.char_class}) - Level {self.level}, HP: {self.health}, Abilities: {self.abilities}"
warrior = Character("Aragorn", "Warrior")
mage = Character("Gandalf", "Mage")
print(warrior.get_status())
print(mage.get_status())| Concept | Remember |
|---|---|
| Constructor | Special method that runs when object is created |
| __init__ | Python's constructor method name |
| First Parameter | Always self, representing the object being created |
| Initialization | Set up instance variables with starting values |
| Parameters | Accept data to customize each object |
| Default Values | Provide defaults so parameters are optional |
| Validation | Check parameters and raise errors if invalid |
| Automatic Call | __init__ runs automatically when you create object |
Now let's learn about inheritance, where you can create classes based on other classes.
Ready to practice? Try challenges or explore more concepts
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward