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

前端 未结 2 1796
刺人心
刺人心 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:30

    Yes. For example, there is __radd__. Also, there are none for __le__(), __ge__(), etc., but as Joel Cornett rightly observes, if you define only __lt__, a > b calls the __lt__ function of b, which provides a workaround.

    >>> class My_Num(object):
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __radd__(self, other_num):
    ...         if isinstance(other_num, My_Num):
    ...             return self.val + other_num.val
    ...         else:
    ...             return self.val + other_num
    ... 
    >>> n1 = My_Num(1)
    >>> n2 = 3
    >>> 
    >>> print n2 + n1
    4
    >>> print n1 + n2
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'My_Num' and 'int'
    

    Note that in at least some cases it's reasonable to do something like this:

    >>> class My_Num(object):
    ...     def __init__(self, val):
    ...         self.val = val
    ...     def __add__(self, other_num):
    ...         if isinstance(other_num, My_Num):
    ...             return self.val + other_num.val
    ...         else:
    ...             return self.val + other_num
    ...     __radd__ = __add__
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题