DEV Community

Cover image for Python Magic Methods
RedouaneSarouf
RedouaneSarouf

Posted on

Python Magic Methods

In this post i will be demonstrating the use of some of python magic magic methods also known as "dunder" methods and how to implement them in your code.
Magic methods are special methods in Python that start and end with a double underscore, such as init, str, add, and many more. These methods have specific names and purposes, and they enable you to define how instances of your custom classes interact with Python's built-in functions and operators.
Lets explore some of these magic methods.

*1. The Constructure method init: *

It is used to initialize objects attributes.
coding example:

class MyClass:
def init(self, value):
self.value = value

obj = MyClass(42)`

2.The string method str:

the string method define string representation of an object.

class MyClass:
def init(self, value):
self.value = value
def str:
return f'{self.value}"
obj = MyClass(42)

3. Length method len:

This method allows you to get the length of an object of your class making them compatible function like len().

`
class MyList:
def init(self, items):
self.items = items

def __len__(self):
    return len(self.items)
Enter fullscreen mode Exit fullscreen mode

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

`
4. Equal method eq:

This method allows to customize equalities for objects comparison.

`class MyClass:
def init(self, x, y):
self.x = x
self.y = y

def __eq__(self, other):
    if isinstance(other, MyClass):
        return self.x == other.x and self.y == other.y
Enter fullscreen mode Exit fullscreen mode

c1 = MyClass(5, 6)
c2 = MyClass(2, 3)
c3 = MyClass(5, 6)
print(c1==c2) # False
print(c1==c3) # True`

In Conclusion Python magic methods are the very powerful tool you can use to customize your classes and making them more flexible. They enable you to define how objects behave in various contexts, from initialization to string representation, arithmetic operations, and more. Magic methods empower you to write clean, readable, and powerful Python code, elevating your programming skills to the next level.

Top comments (0)