Python Magic Methods

What are python magic methods?

In Python, magic methods are special methods that allow you to define how instances of your class behave when used with certain built-in Python functions or operators. These methods have a double underscore (__) before and after their names; hence they are also known as Dunder Methods.

Here are some examples of commonly used magic methods:

  • __init__: Initializes an instance of a class with specified arguments.
  • __str__: Returns a string representation of the instance.
  • __len__: Returns the length of the instance.
  • __add__: Defines behavior for the addition operator (+).
  • ___sub___: Defines behavior for the subtraction operator (-).
  • __mul__: Defines the behavior for the multiplication operator (*).
  • __eq__: Defines behavior for the equality operator (==).
  • __lt__: Defines behavior for the less-than operator (<).
  • __truediv__: Defines the behavior for floating-point division (/).
  • __mod__: Defines the behavior for mod (%).
  • __pow__: Defines the behavior for power (a ** b).
  • __lshift__: Bit-shift left (<<).
  • __rshift__: Bit-shift right (>>).
  • __xor__: Exclusive or (^).
  • __or__: Or (|).

By implementing these methods, you can customize the behavior of your classes to match your specific requirements. For example, by defining the __add__ method, you can make instances of your class work with the + operator, allowing you to perform addition with instances of your class in a way that makes sense for your particular use case.

Leave a Reply