Python __init__() Method

🐍 Python __init__() Method — Full Guide

The __init__() method in Python is a constructor method.
It automatically runs every time an object is created from a class.


🔍 Why __init__()?

  • It initializes the object’s attributes.

  • Helps set default or custom values when creating objects.


🧠 Basic Syntax

class ClassName:
def __init__(self, parameters):
# initialize attributes

✅ Example 1: Simple __init__() Usage

class Student:
def __init__(self, name, age):
self.name = name
self.age = age

s1 = Student("John", 20)

print(s1.name) # John
print(s1.age) # 20

✔ The arguments "John" and 20 are passed to __init__().


🧠 Understanding self

  • self refers to the current object.

  • It must be the first parameter in every method (not just __init__).


Example with Method

class Car:
def __init__(self, brand, year):
self.brand = brand
self.year = year

def info(self):
print(f"{self.brand} was made in {self.year}")

c = Car("BMW", 2022)
c.info()


🎯 Default Values in __init__()

class Laptop:
def __init__(self, brand, ram="8GB"):
self.brand = brand
self.ram = ram

l1 = Laptop("Dell")
l2 = Laptop("HP", "16GB")

print(l1.ram) # 8GB
print(l2.ram) # 16GB


🧩 Multiple Objects with __init__()

p1 = Student("Amit", 22)
p2 = Student("Riya", 19)

print(p1.name, p1.age)
print(p2.name, p2.age)


🔥 __init__() Can Execute Logic

class Bank:
def __init__(self, balance):
self.balance = balance
print("Bank account created!")

b = Bank(5000)

Output:

Bank account created!

⚙ Without __init__() vs With

❌ Without

class Person:
pass

p = Person()

✔ Works, but no data assignment.


✔ With

class Person:
def __init__(self, name):
self.name = name

p = Person("Raj")
print(p.name)


📌 Optional Parameters

class User:
def __init__(self, username, active=True):
self.username = username
self.active = active

u1 = User("Vipul")
u2 = User("Admin", False)

print(u1.active) # True
print(u2.active) # False


✨ Summary Table

Feature Description
Type Constructor method
Auto Execute Yes, when creating object
First Parameter Always self
Purpose Initialize object attributes

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *