[Python] Can I change the default __add__ method in Python?

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to change the default __add__ method to do something else than just add?

    For example, if the goal is with this line: 5+5 get The answer is 10 or anything else like 0 by changing __add__ to be x-y instead of x+y?

    I know I can change __add__ in my own classes:

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

    def __repr__(self):
    return f'{self.x, self.y}'

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


    v1 = Vec(1,2)
    v2 = Vec(5,3)

    v1+v2
    # (6, 5)


    Can I somehow target the default __add__ method to change its behaviour? I intuitively think that __add__ is defined in each default data type to return specific results, but then again, the __add__ method is what we address when changing it for a specific class, so, is it possible to change the main __add__ logic?

    Something along these lines?

    class __add__():
    ...

    Continue reading...

Compartilhe esta Página