Operator overloading in python with the object on the right hand side of the operator

前端 未结 2 1801
刺人心
刺人心 2020-12-07 00:43

I recently learned about operator overloading in python and I would like to know if the following is possible.

Consider the folowing hypothetica/contrived class.

2条回答
  •  佛祖请我去吃肉
    2020-12-07 01:31

    You have to overload the __radd__ method (right-side addition). Your function should look pretty much the same as your __add__ method, e.g.:

    def __radd__(self, other):
         return self.val + other.val
    

提交回复
热议问题