Python Magic Methods

In Python, magic methods are special methods that start and end with double underscores, also known as dunder methods. These methods are used to provide functionality to objects that are not possible using regular methods.

Here are some commonly used magic methods in Python:

  1. __init__(self, ...): This method is called when an object is created and initialized.
  2. __str__(self): This method is used to return a string representation of the object. It is called when the str() function is used on the object.
  3. __repr__(self): This method is used to return a string representation of the object. It is called when the repr() function is used on the object.
  4. __len__(self): This method is used to return the length of the object. It is called when the len() function is used on the object.
  5. __getitem__(self, key): This method is used to get an item from an object using the square bracket notation.
  6. __setitem__(self, key, value): This method is used to set an item in an object using the square bracket notation.
  7. __delitem__(self, key): This method is used to delete an item from an object using the square bracket notation.
  8. __iter__(self): This method is used to return an iterator for the object. It is called when the iter() function is used on the object.
  9. __next__(self): This method is used to return the next value in the iterator. It is called when the next() function is used on the iterator.
  10. __eq__(self, other): This method is used to check if two objects are equal. It is called when the == operator is used on the objects.
  11. __lt__(self, other): This method is used to check if an object is less than another object. It is called when the < operator is used on the objects.
  12. __add__(self, other): This method is used to add two objects together. It is called when the + operator is used on the objects.
  13. __sub__(self, other): This method is used to subtract one object from another. It is called when the - operator is used on the objects.
  14. __mul__(self, other): This method is used to multiply two objects together. It is called when the * operator is used on the objects.
  15. __div__(self, other): This method is used to divide one object by another. It is called when the / operator is used on the objects.