What is __init__() in Python? | Constructor Made Simple



🔹 What is __init__()?

  • __init__() is a special function in a class.
  • It is called automatically when you create an object.
  • It is used to give values to the object’s variables.

📌 We also call it a constructor.


🔹 Simple Example:

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

p1 = Person("John")
print(p1.name)  # Output: John

🧾 What happens here?

  1. We created a class called Person.
  2. Inside the class, we wrote a __init__() function.
  3. self.name = name means we are saving the name in the object.
  4. We made an object p1 = Person("John"). It runs the __init__() and stores "John" inside it.

🔹 What is self in __init__()?

  • self means this object.
  • Python sends it automatically to every function inside a class.
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

s1 = Student("Arun", 18)
print(s1.name)  # Arun
print(s1.age)   # 18


🔹 You Can Add More Than One Parameter

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

c1 = Car("Toyota", 2020)
print(c1.brand)  # Toyota
print(c1.year)   # 2020


📝 Practice Questions with Answers

❓ Q1: Create a class Book with title and author. Use __init__() to set values and print them.

✅ Answer:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

b1 = Book("Python Basics", "Ravi")
print("Title:", b1.title)
print("Author:", b1.author)


❓ Q2: Create a class Laptop with brand and price. Use __init__() and print details.

✅ Answer:

class Laptop:
    def __init__(self, brand, price):
        self.brand = brand
        self.price = price

lap1 = Laptop("Dell", 50000)
print("Brand:", lap1.brand)
print("Price:", lap1.price)


🔎 Summary

KeywordMeaning
__init__()Constructor — runs when object created
selfRefers to the current object
ObjectA real item created from a class

📣 Coming Next:

➡️ “What is self in Python? | Easy Explanation with Examples”


Comments

Leave a Reply

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