B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Python Dunder Methods (Magic Methods) | LiveCodeProgramming

Python Dunder (Magic) Methods

Dunder methods (short for "double underscore") are special methods in Python that start and end with double underscores, like __init__ or __str__. These are also known as magic methods. They allow objects to behave like built-in types and help customize class behavior.

Dunder methods Python के special methods होते हैं जो double underscore से शुरू और खत्म होते हैं, जैसे __init__ या __str__। इन्हें magic methods भी कहा जाता है।

__init__() - Constructor
class Employee:
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary

e1 = Employee('Aryan', 24, 50000)
print(e1.name)

Output:

Aryan

The __init__ method runs when a new object is created.

ऊपर दिया गया method __init__() - Constructor का उपयोग करके object के behavior को customize करता है।

__str__() - String Representation
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def __str__(self):
        return f'Employee: {self.name}, Salary: {self.salary}'

e1 = Employee('Naincy', 60000)
print(e1)

Output:

Employee: Naincy, Salary: 60000

__str__ defines how the object is printed.

ऊपर दिया गया method __str__() - String Representation का उपयोग करके object के behavior को customize करता है।

__add__() - Custom + Operator
class Employee:
    def __init__(self, salary):
        self.salary = salary
    def __add__(self, other):
        return self.salary + other.salary

e1 = Employee(50000)
e2 = Employee(40000)
print(e1 + e2)

Output:

90000

__add__ lets you add two employee salaries using + operator.

ऊपर दिया गया method __add__() - Custom + Operator का उपयोग करके object के behavior को customize करता है।

__len__() - Custom len()
class Employee:
    def __init__(self, name):
        self.name = name
    def __len__(self):
        return len(self.name)

e1 = Employee('Aryan')
print(len(e1))

Output:

5

__len__ defines behavior of len() on the object.

ऊपर दिया गया method __len__() - Custom len() का उपयोग करके object के behavior को customize करता है।

__eq__() - Equality Check
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary
    def __eq__(self, other):
        return self.salary == other.salary

e1 = Employee('A', 40000)
e2 = Employee('B', 40000)
print(e1 == e2)

Output:

True

__eq__ allows comparison using == between objects.

ऊपर दिया गया method __eq__() - Equality Check का उपयोग करके object के behavior को customize करता है।