Sobes.tech
Junior — Middle

What is the purpose of special methods used to control the behavior of objects in a class?

sobes.tech AI

Answer from AI

In Python, special methods (also called magic methods) are methods with double underscores at the beginning and end of the name, such as __init__, __str__, __add__. They allow controlling the behavior of objects in various situations, such as creation, representation, arithmetic operations, and others.

For example:

  • __init__ initializes an object upon creation.
  • __str__ defines the string representation of an object.
  • __add__ defines the behavior of the + operator for class objects.

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)        # Point(1, 2)
p3 = p1 + p2
print(p3)        # Point(4, 6)

Thus, special methods allow customizing object behavior during standard operations and interactions.