有没有办法能够将 Python 类的实例添加到整数(默认 int
类)。例如,如果我有一个带有魔法方法的类:
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
类中。如果我尝试将 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
类的 __add__
方法。如果您想知道为什么我不只是将 int
添加到 IntType
(例如 IntType(10) + 10
),因为我需要这适用于所有运算符,例如减法(顺序很重要)。我正在使用 Python 3。
最佳答案
为您的 IntType
类实现反向加法 (__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)
不是已定义的操作)。
关于python - 将自定义数字类添加到 Python int 结果为 "TypeError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56333872/