Make my_average(a, b) work with any a and b for which f_add and d_div are defined. As well as builtins

后端 未结 2 2129
感情败类
感情败类 2021-01-16 01:40

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 02:09

    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))
    

提交回复
热议问题