将自定义数字 class 添加到 Python int 结果 "TypeError"

Adding custom number class to Python int results in "TypeError"

有没有办法能够将 Python class 的实例添加到整数(默认 int class)。例如,如果我有一个带有魔术方法的 class:

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

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

# Works
print(IntType(10) + 10)

# Doesn't Work
print(10 + IntType(10))

我无法将我的 IntType 添加到内置 int class。如果我尝试将 IntType 添加到整数,我会收到以下错误:

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print(10 + IntType(10))
TypeError: unsupported operand type(s) for +: 'int' and 'IntType'

我能想到的唯一方法就是以某种方式更改 int class' __add__ 方法。如果您想知道为什么我不只是将 int 添加到 IntType(例如 IntType(10) + 10)是因为我需要它对所有运算符都起作用,例如减法(其中顺序很重要)。我正在使用 Python 3.

为您的 IntType class 实施反向加法 (__radd__) 应该可以解决这个问题:

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

>>> IntType(10) + 10 == 10 + IntType(10)
True

这是 Python 在所有其他方法都失败时尝试使用的操作(即,int.__add__(IntType) 不是已定义的操作)。