What is Python Dunder?

What is Python Dunder?

"dunder" is short for "double underscore"

Table of contents

No heading

No headings in the article.

In Python, the term "dunder" is short for "double underscore" or "dunder mifflin", and it is often used to refer to special methods that have two leading and two trailing underscores. These methods are also known as "magic methods" because they allow you to define how built-in Python functions and operators should behave when used with custom classes. For example, the __init__ method is a special method that is called when an object is initialized, and it allows you to set the initial values for that object, __str__ for string representation, and __len__ for determining the length of an object.

Here is an example of how dunder methods, also known as "magic" methods, can be implemented in Python:

class MyClass:
    def init(self, value):
        self.value = value
    def __str__(self):
        return "MyClass with value: {}".format(self.value)

    def __lt__(self, other):
        return self.age < other.age

    def __eq__(self, other):
        if isinstance(other, MyClass):
            return self.value == other.value
        return False


#Create an instance of MyClass

my_obj = MyClass(5)

#Print the string representation of the object

print(str(my_obj)) # 5

# Creating two objects
my_object1 = MyClass("Dias", 30)
my_object2 = MyClass("Ake", 25)

# Check if it opposite sides is less than the other
print(my_object1 < my_object2) # False

print(my_object2 < my_object1) # True
#Check if two objects are equal


another_obj = MyClass(5) 
print(my_obj == another_obj) # True

# Check if an object is equal to a non-MyClass object

print(my_obj == 5) # False

In this example, the init() method is used to initialize the object with a value, the str() method is used to define the string representation of the object, and the eq() method is used to define how the object should be compared to other objects. These dunder methods are called automatically by the Python interpreter when certain operations are performed on the object.

Thanks for taking the time to read this.

You can follow me on Twitter, Github, Linkedin