In short: what I want is for the majority of mathematical functions I\'ve written (e.g., my_average(a, b)
) to work with any a
and b
fo
This might be an idea:
import operator
f_add = {}
def add(a,b):
return f_add.get(type(a),operator.add)(a,b)
# example
class RGB:
def __init__(self, r,g,b):
self.r, self.g, self.b = (r,g,b)
def __str__(self):
return '<%s,%s,%s>'%(self.r,self.g,self.b)
f_add[RGB] = lambda a,b: RGB(a.r+b.r,a.g+b.g,a.b+b.b)
print(add(RGB(0.4,0.7,0.1), RGB(0.1, 0.2, 0.5)))
print(add(4,5))