Dunder in python

Dunder in python

Dunder stands for "double underscore." In Python, these are special methods (or functions) that have double underscores at the beginning and end of their names. They're also called "magic methods."

Imagine you're playing with a special toy. It has buttons that do cool things when you press them. In Python, dunder methods are like these buttons—they make your code do cool and special things.

To check all the dunder methods (special methods) of a class or an object in Python, you can use the dir() function. This function lists all the attributes and methods of the object, including the dunder methods.

Here's how you can do it:

class MyClass:
    def __init__(self, name):
        self.name = name

    def my_method(self):
        print("Hello")

# Create an instance of the class
my_instance = MyClass("Example")

# Use dir() to list all attributes and methods of the instance, including dunder methods
print(dir(my_instance))

This will print a list of all the attributes and methods of the my_instance object, including the special dunder methods like __init__, __str__, __repr__, and many others.

For example:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'my_method', 'name']

This command works with any object or class, so you can use it to explore the dunder methods available in any part of your code.

Special Dunder Methods

  1. __init__:

    • Think of this as the starting point of a toy. When you get a new toy, you have to set it up before you play with it.

    • In Python, __init__ is used to set up a new object when you create it. It’s called the constructor.

    class Toy:
        def __init__(self, name):
            self.name = name  # Set up the toy with its name

    my_toy = Toy("Robot")
    print(my_toy.name)  # Output: Robot
  1. __main__:

    • Imagine you're deciding whether to play inside or outside. You check the weather first to decide.

    • In Python, __main__ helps decide if your code should run as a standalone program or be used by other programs.

        if __name__ == "__main__":
            print("This code is running directly!")
        else:
            print("This code is being imported!")
      

When you run the file directly, __name__ is __main__, so it prints "This code is running directly!"

Summary

  • Dunder Methods: Special methods with double underscores like __init__ and __main__ that do important things in Python.

  • __init__: Sets up a new object with its initial values, like setting up a new toy.

  • __main__: Decides if the code should run directly or be used by other programs, like deciding to play inside or outside.