【问题标题】:Adding custom number class to Python int results in "TypeError"将自定义数字类添加到 Python int 会导致“TypeError”
【发布时间】: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 属于哪个类,这样你的类就可以同时使用TypeIntint -> return self.value + other if isinstance(other, int) else self.value + other.value
  • @jfaccioni 你的权利我可以...

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


【解决方案1】:

为您的 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) 不是已定义的操作)。

【讨论】:

  • 这成功了!虽然我使用return other + self.value 来保留订单。 (用于减法和除法)
  • 您也可以简单地按照正则加法来实现反向加法(至少对于另一个无关紧要的数学运算):def __radd__(self, other): return self.__add__(other)
猜你喜欢
  • 2018-09-15
  • 2019-03-20
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 2021-05-16
  • 2016-08-11
  • 2022-01-25
  • 2015-06-23
相关资源
最近更新 更多