Nearby lessons

84 of 108

Python - Constructor

What Is a Constructor?

A constructor is a special method used to initialize an object.

In Python, the constructor method is named __init__.

Why Is It Used?

Constructors are mainly used to declare and initialize instance variables when an object is created.

Example

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

Constructor Behavior

  • Executed automatically when the object is created
  • Runs only once for each object
  • Can take arguments
  • Is optional

Summary

Term Meaning
__init__Constructor method
selfRefers to current object
ConstructorInitializes instance variables

🧠 Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!Python - **init** Method