I want to make it possible to overload the + operator in such a way that it would be possible to add an object to an object, and add a number to an object.

class Fff: def __init__(self,x,y): self.x = x self.y = y def __add__(self,obj): return Fff(self.x + obj.x,self.y + obj.y) def __add__(self,v): return Fff(self.x + v,self.y + v) def show(self): print self.x,' : ',self.y f1 = Fff(1,2) f2 = Fff(5,5) result = f1 + f2 result2 = f1 + 2 result.show() result2.show() 

    1 answer 1

    There is no overload of functions in python. But you can implement different function behaviors depending on the type of argument passed. Use something similar instead of both of your addition methods.

     def __add__(self, arg): if isinstance(arg, numbers.Number): return Fff(self.x + arg, self.y + arg) else: return Fff(self.x + arg.x, self.y + arg.y)