Sobes.tech
Middle

What methods __add__, __mul__, __sub__, and __truediv__ do you know and how can they be used in Python?

sobes.tech AI

Answer from AI

These are special "magic" or "dandom" methods used for operator overloading. They allow class objects to behave like standard numeric types when performing arithmetic operations.

  • __add__(self, other): Overloads the + operator. Called when adding objects (self + other).
  • __mul__(self, other): Overloads the * operator. Called when multiplying objects (self * other).
  • __sub__(self, other): Overloads the - operator. Called when subtracting objects (self - other).
  • __truediv__(self, other): Overloads the / operator. Called for "true" division of objects (self / other), returning a float.

Example of usage in the Vector class:

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

    def __add__(self, other):
        # Addition of two vectors
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        # Addition of a vector with a number (scalar multiplication)
        elif isinstance(other, (int, float)):
            return Vector(self.x + other, self.y + other)
        else:
            return NotImplemented # Indicates that the operation is not supported for this type

    def __mul__(self, other):
        # Multiplication of vector by scalar
        if isinstance(other, (int, float)):
            return Vector(self.x * other, self.y * other)
        # Dot product of two vectors
        elif isinstance(other, Vector):
            return self.x * other.x + self.y * other.y
        else:
            return NotImplemented

    def __sub__(self, other):
        # Subtraction of vectors
        if isinstance(other, Vector):
            return Vector(self.x - other.x, self.y - other.y)
        # Subtraction of a number
        elif isinstance(other, (int, float)):
            return Vector(self.x - other, self.y - other)
        else:
            return NotImplemented

    def __truediv__(self, other):
        # Division of vector by scalar
        if isinstance(other, (int, float)) and other != 0:
            return Vector(self.x / other, self.y / other)
        else:
            return NotImplemented # Division by zero or non-numeric type is not supported

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

# Usage examples:
v1 = Vector(1, 2)
v2 = Vector(3, 4)

sum_vector = v1 + v2 # Calls v1.__add__(v2)
print(f"v1 + v2 = {sum_vector}")

scaled_vector = v1 * 5 # Calls v1.__mul__(5)
print(f"v1 * 5 = {scaled_vector}")

diff_vector = v2 - v1 # Calls v2.__sub__(v1)
print(f"v2 - v1 = {diff_vector}")

divided_vector = v1 / 2.0 # Calls v1.__truediv__(2.0)
print(f"v1 / 2.0 = {divided_vector}")

dot_product = v1 * v2 # Calls v1.__mul__(v2)
print(f"v1 * v2 (dot product) = {dot_product}")