【发布时间】:2019-10-13 11:45:55
【问题描述】:
有没有办法能够将 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。
【问题讨论】:
-
左操作数是定义 __add__ 的操作数。为此,您必须覆盖 int。如果你想让它为 2 个 IntTypes 工作,你应该做
return self.value + other.value。 -
这是我能做到这一点的唯一方法吗?这样做的问题是,现在,如果我分发我的程序,它会变得困难十倍,因为我必须找到一种方法进入 python 内部并更改
__add__方法。 -
@CristiFati 如果我添加了
return self.value + other.value,我将无法将普通整数添加到修改后的整数类,因为它没有属性value,所以我必须使用@987654336 @'s 让它工作,这更慢。 -
@MonLiH 你可以检查
other属于哪个类,这样你的类就可以同时使用TypeInt和int->return self.value + other if isinstance(other, int) else self.value + other.value。 -
@jfaccioni 你的权利我可以...
标签: python python-3.x class typeerror magic-methods