logo

Summary of Python Special Methods 📂Programing

Summary of Python Special Methods

Overview

In Python, you can define operations on a class’s instance by defining methods with specific names. These methods are called special methods, also known as magic methods. By prefixing and suffixing these names with __, they are sometimes referred to as dunder methods (double underscore method).

__init__ and __call__

  • __init__: A method for initializing an instance. Its contents are automatically executed when defining an instance.
  • __call__: Executed when the instance is called. It allows it to be used like a function.
class Add:

    def __init__(self, a, b):
        self.a = a
        self.b = b
        print(f"a = {self.a}, b = {self.b}")

    def __call__(self):
        c = self.a + self.b
        print(f"{self.a} + {self.b} = {c}")

>>> c = Add(1,3)
a = 1, b = 3

>>> c()
1 + 3 = 4