【问题标题】:Operator overloading in python with the object on the right hand side of the operatorpython中的运算符重载,运算符右侧的对象
【发布时间】:2012-05-16 11:08:39
【问题描述】:

我最近了解了python中的运算符重载,我想知道以下是否可行。

考虑以下假设/人为的类。

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

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

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

这些将按预期工作。我也知道现在的写法我做不到这个

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

这有什么问题吗?我知道这个例子是人为的,但是我有一个应用程序,如果在我进行运算符重载时,我定义运算符的类可以出现在运算符的右侧,它将非常有用。这在python中可能吗?

【问题讨论】:

    标签: python operator-overloading


    【解决方案1】:

    是的。例如,有__radd__。此外,there are none 用于 __le__()__ge__() 等,但正如 Joel Cornett 正确观察到的那样,如果您仅定义 __lt__a > b 调用 __lt____lt__ 函数,它提供了一种解决方法.

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

    请注意,至少在某些情况下,这样做是合理的:

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

    【讨论】:

    • 谢谢。 radd 是唯一允许这样做的吗?我需要为我的应用程序重载的特定运算符是 >> 和
    • 不。你点击链接了吗?还有__rrshift__等等。
    • 通过控制为每个类定义的运算符,可以在有限的范围内进行正确比较。例如,如果 A 和 B 只定义了 lt。 AA会调用属于小端的方法。
    • 有什么方法可以改变操作符的关联性吗?例如,我可以让 >> 运算符右关联吗?
    • @martega,那个,我高度怀疑。但我真的不知道。
    【解决方案2】:

    您必须重载__radd__ 方法(右侧添加)。你的函数看起来应该和你的 __add__ 方法几乎一样,例如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      相关资源
      最近更新 更多