Sobes.tech
Junior — Middle

What are special methods in a programming language and how are they implemented?

sobes.tech AI

Answer from AI

In Python, special methods are methods with names enclosed in double underscores, such as __init__, __str__, __add__. They allow defining the behavior of objects during standard operations like creation, string conversion, arithmetic operations, etc.

They are implemented by defining the corresponding methods within a class. For example:

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

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

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

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)  # Vector(4, 6)

Thus, special methods allow integrating user-defined objects with the syntax and standard functions of the language.