Sobes.tech
Junior — Middle

Can you name the main special methods in Python and their purpose?

sobes.tech AI

Answer from AI

In Python, special methods (or magic methods) are methods with double underscores at the beginning and end of the name, which allow objects to behave like built-in types.

The main ones include:

  • __init__(self, ...) — constructor, called when creating an object.
  • __str__(self) — returns a string representation of the object for the user.
  • __repr__(self) — returns an official string representation of the object, useful for debugging.
  • __len__(self) — returns the length of the object.
  • __getitem__(self, key) — allows accessing elements of the object by index or key.
  • __setitem__(self, key, value) — allows assigning values by index or key.
  • __iter__(self) — returns an iterator for the object.
  • __eq__(self, other) — defines the behavior of the equality operator ==.
  • __add__(self, other) — defines the behavior of the addition operator +.

Example of using __str__ and __repr__:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"Point ({self.x}, {self.y})"

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"

p = Point(1, 2)
print(str(p))  # Point (1, 2)
print(repr(p)) # Point(x=1, y=2)
Can you name the main special methods in Python and… - sobes.tech