← Back to Python Course | Chapter 7: OOP | Lesson 9 of 11

Python Magic Methods

Magic methods special hidden-name methods हैं जो आपके objects को Python के normal tools, जैसे plus signs या len(), के साथ काम करने देते हैं। यह अपने toy को किसी familiar game में शामिल होना सिखाने जैसा है।
Syntax
python
class ClassName:
    def __init__(self, ...):
        # constructor
    def __str__(self):
        return "text"
    def __add__(self, other):
        # operator +

Magic Methods क्या हैं?

Magic methods (जिन्हें dunder methods भी कहा जाता है, अपने __init__ जैसे double underscores के लिए) special hooks हैं जिन्हें Python built-in operations के लिए अपने-आप call करता है — __init__ define करना आपको object construction customize करने देता है, जबकि दूसरे dunders printing, comparison, arithmetic, और बहुत कुछ customize करने देते हैं।

उदाहरण: What are Magic Methods?

python
class Point:
    def __init__(self, x, y):  # __init__ is a magic method Python calls on creation
        self.x = x
        self.y = y

p = Point(1, 2)
print(p.x, p.y)

Operator Overloading

किसी class पर __add__(self, other) define करना + operator को आपके अपने objects पर काम करने देता है — दो Vector objects लिखिए और v1 + v2 पर्दे के पीछे v1.__add__(v2) call करता है, जिससे आप summed components वाला एक नया Vector लौटा सकते हैं, Python के TypeError raise करने की बजाय।

उदाहरण: Operator Overloading

python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __add__(self, other):  # called automatically when using +
        return Vector(self.x + other.x, self.y + other.y)

v = Vector(1, 2) + Vector(3, 4)  # triggers Vector.__add__
print(v.x, v.y)

Comparison Magic Methods

__eq__ को overload करना आपको define करने देता है कि आपकी class के लिए '==' का क्या मतलब है (जैसे दो Point objects को identity से नहीं बल्कि उनके x/y coordinates से compare करना), और __lt__ '<' define करता है ताकि sorted() और min() जैसे built-ins जान सकें कि आपके objects को कैसे order करना है।

उदाहरण: Comparison Magic Methods

python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __eq__(self, other):  # defines what == means for Point
        return self.x == other.x and self.y == other.y

print(Point(1, 2) == Point(1, 2))  # compares coordinates, not identity

Length और Container Methods

__len__ define करने से आपकी custom class पर len(my_object) काम करता है, और __getitem__ उसे square-bracket indexing (my_object[0]) support करने देता है — साथ मिलकर ये दोनों अक्सर किसी custom class को कहीं भी list या dict की जगह इस्तेमाल करने लायक बना देते हैं।

उदाहरण: Length and Container Methods

python
class Basket:
    def __init__(self, items):
        self.items = items
    def __len__(self):  # makes len(basket) work
        return len(self.items)
    def __getitem__(self, index):  # makes basket[0] work
        return self.items[index]

b = Basket(["apple", "banana"])
print(len(b), b[0])

Objects को Callable बनाना

__call__ implement करने से आप किसी instance को सीधे function की तरह invoke कर सकते हैं — my_object() — जो उन objects के लिए उपयोगी है जो कुछ configurable behavior wrap करते हैं, जैसे एक class जो settings याद रखती है और फिर call होने पर एक computation चलाती है।

उदाहरण: Making Objects Callable

python
class Multiplier:
    def __init__(self, factor):
        self.factor = factor
    def __call__(self, x):  # lets the instance be called like a function
        return x * self.factor

times3 = Multiplier(3)
print(times3(10))  # calls times3.__call__(10)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.