Sobes.tech
Junior — Middle

Can you explain the mechanism of special methods that are called automatically in certain situations in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming in Python, special methods (often called "magic" or "dunder" methods, i.e., with double underscores, such as __init__, __str__, __add__) are called automatically in certain situations.

For example:

  • __init__ is called when creating an object (constructor).
  • __str__ is called when converting an object to a string (e.g., when calling print).
  • __add__ is called when using the + operator between objects.

This allows overriding the behavior of standard operations for your classes.

Example:

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

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

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1)        # Outputs: Point(1, 2)
p3 = p1 + p2
print(p3)        # Outputs: Point(4, 6)

Thus, special methods allow integrating custom classes with the syntax and behavior of the language.