I am using python 3 (3.3, but I'm interested of any nice solution, even if it's only python 3.4 or more). I want to create a custom class with conditional overloading operator like that:
class test :
def __init__(self,overload) :
if overload :
self.__add__=lambda x,y : print("OK")
self.f=lambda : print(True)
def f(self) : print(False)
t=test(False)
t.f() #print False as expected
u=test(True)
u.f() #print True as expected
u+u #fails as if it was not implemented
After some digging, I realized that operator + does not call __add__ on the object, but on the class. Hence, I can't do it like that (or can I)?
So I can define something like that :
class test :
def __init__(self,overload) :
self.overload=overload
def __add__(self,other) :
if self.overload : print("OK")
else #FAILURE
def f(self) : print(self.overload)
But what can I put into the FAILURE statement such that it fails exactly like if it was not implemented? For example, if it fails, I'll be happy if it tried __radd__ on the second operator.