In Python how to redefine an operator?
Mar 29, 9:56pm

In Python, you can redefine an operator (also known as operator overloading) for your custom classes by implementing special methods, often called dunder methods (double underscore methods). These methods allow you to define how operators behave when used with instances of your class.

Common Operator Overloading Methods

+
__add__
Addition
-
__sub__
Subtraction
*
__mul__
Multiplication
/
__truediv__
Division
==
__eq__
Equality
<
__lt__
Less than
>
__gt__
Greater than
<=
__le__
Less than or equal
>=
__ge__
Greater than or equal
+=
__iadd__
In-place addition
[]
__getitem__
Indexing
()
__call__
Calling an instance

Example: Overloading + for a Custom Class

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

    # Overloading the + operator
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    # Overloading the * operator
    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    # Overloading the == operator
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    # Overloading the string representation
    def __str__(self):
        return f"Vector({self.x}, {self.y})"

# Usage
v1 = Vector(2, 3)
v2 = Vector(4, 5)
v3 = v1 + v2
v4 = v1 * 2

print(v3)  # Output: Vector(6, 8)
print(v4)  # Output: Vector(4, 6)
print(v1 == Vector(2, 3))  # Output: True

Key Points

  • __add__ is called when you use + on instances of your class.
  • __mul__ is called when you use * on instances of your class.
  • __eq__ is called when you use == to compare instances.
  • __str__ is called when you use print() or str() on an instance.

Want to see more examples or a specific operator? Let me know!

Mar 29, 9:56pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.