pythonpython-3.xoverridingoverloadingmagic-methods

Python, overloading magic methods, multiple usage for same magic method


Is it possible to overload magic methods or get a similar result as in e.g. overloading methods in C# for magic methods in python ? or is it simply another handicap of this language and it is impossible at this moment as in the past "types" used to be ;)

def __init__(self, x:float, y:float, z:float) -> None:
    self.x = x
    self.y = y
    self.z = z
    
def __add__(self, other:'Vector') -> 'Vector':
    return Vector(self.x + other.x, self.y + other.y, self.z + other.z)

def __add__(self, other:float) -> 'Vector':
    return Vector(self.x + other, self.y + other, self.z + other)

I have tried to test it and...

vector_one = Vector(1, 2, 3)
vector_two = Vector(4, 5, 6)

print(vector_one + vector_two)

enter image description here


Solution

  • No, it's not possible to automatically overload, but you can check for type and proceed accordingly:

    from typing import Union
    
    class Vector:
        # ...
    
        def __add__(self, other: Union['Vector', float]) -> 'Vector':
            if type(other) == Vector:
                return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
            elif type(other) == float:
                return Vector(self.x + other, self.y + other, self.z + other)
            else:
                raise TypeError   # or something else