Ticker

6/recent/ticker-posts

Dunder/Magic Methods in Python

Dunder/Magic Methods in Python

Introduction:
Dunder (double-underscore) or magic methods are special methods in Python that enable developers to define specific behaviors for classes. They are identified by their double underscores at the beginning and end of their names. These methods are automatically called by the interpreter in response to certain operations or actions on objects.

Commonly Used Dunder Methods:

1. __init__:
This magic method is used to initialize an object when it is created. It is called automatically when an instance of the class is created.

Example:

python
class MyClass:
def __init__(self, value):
self.value = value

obj = MyClass(42)

2. __str__ and __repr__:
These methods define how an object is represented as a string when printed or called by the str() and repr() functions, respectively.

Example:

python
class MyClass:
def __init__(self, value):
self.value = value

def __str__(self):
return f"MyClass with value: {self.value}"

def __repr__(self):
return f"MyClass({self.value})"

obj = MyClass(42)
print(str(obj)) # Output: "MyClass with value: 42"
print(repr(obj)) # Output: "MyClass(42)"

3. __len__:
This method allows you to customize the behavior of the len() function for objects of the class.

Example:

python
class MyList:
def __init__(self, data):
self.data = data

def __len__(self):
return len(self.data)

my_list = MyList([1, 2, 3, 4, 5])
print(len(my_list)) # Output: 5

4. __add__:
With this method, you can define how instances of your class behave when the + operator is used with them.

Example:

python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)
result = p1 + p2
print(result.x, result.y) # Output: 4 6

Conclusion:
Dunder methods in Python provide a powerful way to customize the behavior of classes and objects. By implementing these methods, you can define how instances of your classes interact with various built-in functions and operators.

Post a Comment

0 Comments