python - 将自定义数字类添加到 Python int 结果为 "TypeError"

标签 python python-3.x class typeerror magic-methods

有没有办法能够将 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/

相关文章:

python - 使用pyaudio创建语音识别程序但出现问题

python - 访问上一个列表的列表项

python - 保留满足条件的行和相邻行

python - json.dumps() 适用于 python 2.7 但不适用于 python 3

Python用星号替换字符串的某些部分

Python:如何为子类中的属性设置默认值

python - 如何在 py.test 中重复测试模块?

python - 递归函数变量混淆

c++ - 如何在初始化时仅针对特定对象继承和更改类?

java - 用java反射实例化私有(private)内部类