DEV Community

Cover image for Extend python with magic(part-1)
SaptakBhoumik
SaptakBhoumik

Posted on

Extend python with magic(part-1)

Hi everyone,
In this post I will show you something magical in python 😏.

What am I even talking about?

Well I am talking about magic/dunder method. They are a very useful feature of python and allows you to write code that is more readable,less verbose and efficient. In my previous post(you can read it here here) I had talked about operator overloading in python and those are basically magic methods. It is not possible to cover every dunder method in one post so I will cover only a few.

__init__

Most of you already know about it and I am covering it only because it is very important. This method is called automatically when you create any instance of the object.
The code

class Object:
    def __init__(self):
        print("Object innitialized")

x=Object()
Enter fullscreen mode Exit fullscreen mode

Breaking it down
__init__(self)-This is the method that is called when you create an instance of an object. In this case it prints a string
x=Object()-Here we are initializing x with an instance of the object

__repr__

This method returns a string that is printed when you try to print the instance of an object. It is helpful for debugging purposes
The code

class Object:
    def __init__(self,value):
        self.x=5
    def __repr__(self):
        return f"Value is {self.x}"
x=Object(6)
print(x)
Enter fullscreen mode Exit fullscreen mode

Breaking it down
__repr__(self) - It returns the string to be printed and doesn't take any argument
On running the above code you will get Value is 6 as result. If you want to get the string representation instead of printing it then you can use repr(x)

__len__

This method returns the length of the instance of the object when you use the lens() function on it.
The code

class Object:
    def __len__(self):
        return 4
x=Object()
print(len(x))
Enter fullscreen mode Exit fullscreen mode

Breaking it down
__len__(self)-This method returns the length of the object and that's it. It must return an integer and should not take any argument.
The code

class Object:
    def __len__(self):
        return 4
x=Object()
print(len(x))
Enter fullscreen mode Exit fullscreen mode

Breaking it down
__len__(self)-This returns the length of the object and that's it. It should always return a number and should never take any argument

Conclusion

Magic method are extremely powerful and there are many of them. It is not possible for me to cover all of them in one post so I will post more about them in the future. If you have enjoyed this please read my post about peregrine
Thanks for reading <3

Oldest comments (0)