पायथन में, Constructor एक विशेष प्रकार का method होता है जिसे class के object को initialize करने के लिए इस्तेमाल किया जाता है। जब भी हम class के object को create करते हैं, तो constructor अपने आप call हो जाता है।
दूसरे शब्दों में कहें तो, “Constructor एक विशेष प्रकार का function होता है जो class के object को create करते समय अपने आप call होता है।”
जब भी हम कोई class बनाते हैं और उसके object को create करते हैं, तो हमें object की properties को initialize करने की ज़रूरत होती है। Constructor यह काम अपने-आप कर देता है, जिससे हमें हर बार खुद से initialization करने की जरूरत नहीं पड़ती।
Constructor को define कैसे करते हैं?
Python में constructor को __init__() method से define किया जाता है। इसका syntax कुछ इस प्रकार होता है:-
class MyClass:
def __init__(self, value):
self.value = value
यहां, __init__() method को constructor कहा जाता है और self पैरामीटर अपने आप Python के द्वारा pass किया जाता है। value को हम object के creation के दौरान pass कर सकते हैं।
Constructor का Example:
अब हम एक simple example देखते हैं, जिसमें constructor का इस्तेमाल किया गया है।
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Object creation
person1 = Person("Yugal", 29)
person1.display()
Constructor के प्रकार
पायथन में Constructor के दो प्रकार होते हैं:-
- Default Constructor
- Parameterized Constructor

1:- Default Constructor
Default Constructor वह होता है जिसमें कोई parameter पास नहीं किया जाता। यह बिना किसी initialization के object को create करता है।
Example:–
class Example:
def __init__(self): # Default Constructor
self.message = "यह एक Default Constructor है।"
def display(self):
print(self.message)
# Object बनाना
obj = Example()
obj.display()
Output:-
यह एक Default Constructor है।
2:- Parameterized Constructor
Parameterized constructor वह होता है जो parameters को accept करता है और उन्हें object को initialize करने के लिए इस्तेमाल करता है।
Example:-
class Student:
def __init__(self, name, age): # Parameterized Constructor
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
# Object बनाना
student1 = Student("Rahul", 21)
student2 = Student("Anjali", 20)
student1.display()
student2.display()
Output:-
Name: Rahul, Age: 21
Name: Anjali, Age: 20
इसे पढ़ें:-