python:反转魔法方法中影响运算符的元素

python: reverse the elements of magic methods that affect operators

我正在尝试创建一个 python 对象,该对象可以包含任意小数位的数字。一切正常,但我在使对象与数学运算符交互时遇到了问题。这是重现错误的方法:

class Value():
  def __init__(self,value):
    self.value = value
  def __add__(self,other):
    return self.value + other

x = Value(5)
print(x+2) # this works fine: 7
print(2+x) # this doesn't work: TypeError: unsupported operand type(s) for +: 'int' and 'Value'

所有其他数学运算都会发生同样的事情,我可以做些什么来避免这种情况吗?

您错过了实施 __radd__:

class Value():
  def __init__(self,value):
    self.value = value
  def __add__(self,other):
    return self.value + other
  __radd__ = __add__

x = Value(5)
print(x+2)
# 7
print(2+x)
# 7

有关 Python 文档中讨论 emulating numeric types and the operator 模块的更多信息。

实施__radd__ (or other __r* methods):

class Value:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        return self.value + other

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


x = Value(5)
print(x + 2)
print(2 + x)

你应该使用 __radd____r*__ 方法是 python 神奇的方法,当一个对象从另一个对象的 __add__ 中获取时,它会产生一些东西。
试试这样的东西。

class Value(): 
   def __init__(self,value): 
      self.value = value 
   def __add__(self,other): 
      return self.value + other 
   __radd__ = __add__ 

x = Value(5) 
print(x+1 == 1+x) // True