Python special methods.

Moses Mwangi
2 min readJul 12, 2023

--

A set of predefined methods with double underscores (also known as dunder methods) that provide functionality to classes and objects in a special way.

Objects Special methods.

  1. __init__(self, ...): The constructor method that is automatically called when an object is created. It initializes the object and sets its initial state.
  2. __str__(self): Returns a string representation of the object that is intended to be human-readable. It is called by the str() function or when an object is used in a print statement or formatted string.
  3. __repr__(self): Returns a string representation of the object that is mainly used for debugging and development purposes. It should ideally be a valid Python expression that could be evaluated to recreate the object. It is called by the repr() function or when the object is displayed in the Python interactive interpreter.
  4. __len__(self): Returns the length of the object, allowing it to be used with the len() function.
  5. __getitem__(self, key): Allows objects to support indexing and enables accessing elements using square brackets, like obj[key].
  6. __setitem__(self, key, value): Allows objects to support assignment to elements using square brackets, like obj[key] = value.
  7. __delitem__(self, key): Allows objects to support deletion of elements using the del statement and square brackets, like del obj[key].
  8. __contains__(self, item): Returns True or False depending on whether the object contains the specified item. It enables the use of the in and not in operators.
  9. __iter__(self): Returns an iterator object that allows iteration over the object's elements. It is used in for loops and other iterable contexts.
  10. __next__(self): Returns the next item from an iterator object created by __iter__(). It is used in conjunction with the __iter__() method to implement iteration.
  11. __call__(self, ...): Allows objects to be called as if they were functions. It is invoked when the object is followed by parentheses, like obj().

--

--