Python: Magic Methods

in #python3 years ago (edited)

 Introduction

They are special methods with fixed names. These methods have double underscores at the beginning and the end of their name. Magic methods are sometimes called dunder methods.

The magic in magic methods is that we don't have to explicitly call it. When an instance of a class is created the magic methods are automatically called behind the screen.

__call__ method

It enables us to write classes whose instances behave like functions. Both functions and the instances of such classes are called callable. A callable object behaves like a function. An instance can be a callable object if the class has __call__ method. 

class A:
   def __init__(self):
       print("An instance of A was initialized")
   def __call__(self, *args, **kwargs):
       print("Arguments are:", args, kwargs)


x = A()
print("now calling the instance:")
x(3, 4, x=11, y=10)
print("Let's call it again:")
x(3, 4, x=11, y=10)


Output:
An instance of A was initialized
now calling the instance:
Arguments are: (3, 4) {'x': 11, 'y': 10}
Let's call it again:
Arguments are: (3, 4) {'x': 11, 'y': 10}


To check the list of all magic methods in a class, print the following command

class MyClass:
    pass

dir(Myclass)


For more info and examples please refer to the following link: https://www.python-course.eu/python3_magic_methods.php