python中的运算符重载,对象在运算符的右侧 [英] Operator overloading in python with the object on the right hand side of the operator

查看:106
本文介绍了python中的运算符重载,对象在运算符的右侧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解了python中的运算符重载,我想知道是否有可能实现以下目的.

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.

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

我知道上面写的方式,我可以做这样的事情

I know that the way that's written above, I can do things like this

n1 = My_Num(1)
n2 = My_Num(2)
n3 = 3
print n1 + n2
print n1 + n3

,这些将按预期工作.我也知道目前的写作方式我无法做到

and those will work as expected. I also know that the way it's currently written I can't do this

n1 = My_Num(1)
n2 = 2
print 2 + n1

这附近还有吗?我知道这个示例是人为设计的,但是我有一个应用程序,如果我进行运算符重载时,定义该运算符的类可以出现在运算符的右侧,它将非常有用.在python中有可能吗?

Is there anyway around this? I know this example is contrived but I have an application in which it would ve very useful if when I did operator overloading, the class for which I define the operator can appear on the right hand side of operator. Is this possible in python?

推荐答案

是.例如,有 __radd__ .另外,对于__le__()__ge__()等,没有 .,但正如Joel Cornett正确地观察到的那样,如果仅定义__lt__,则a > b会调用b__lt__函数,这提供了一种解决方法.

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__

这篇关于python中的运算符重载,对象在运算符的右侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆