首页 > 解决方案 > 你如何在 python 中使用用户定义的类来支持混合算术?

问题描述

我很好奇如何在 python 中使用用户定义的类来支持混合算术。文档状态

Python 完全支持混合算术:当一个二元算术运算符具有不同数值类型的操作数时,具有“较窄”类型的操作数被扩大到另一个,其中整数比浮点窄,浮点比复数窄。

我试图重新创建的行为可以用 numpy 看到

import numpy as np

a = np.array([1,2,3])

a + 5
Out[3]: array([6, 7, 8])

5 + a
Out[4]: array([6, 7, 8])

如果我尝试使用用户定义的类来做到这一点,我会得到这样的东西

from decimal import Decimal


class MyType:
    def __init__(self, value):
        self.value = Decimal(str(value))
    def __repr__(self):
        return f'<MyType {self.value}>'

    def __add__(self, other):
        if not isinstance(other, MyType):
            other = MyType(other)
        return MyType(self.value + other.value)

然后当第一个加法参数是浮点数而不是我的类时,尝试做类似的事情会出错。

a = MyType(.1)

a + 5
Out[14]: <MyType 5.1>

5 + a
Traceback (most recent call last):

  File "<ipython-input-15-35e25b55bb62>", line 1, in <module>
    5 + a

TypeError: unsupported operand type(s) for +: 'int' and 'MyType'

标签: pythonpython-3.x

解决方案


在 python 中,您可以同时定义__add____radd__,请参阅https://docs.python.org/3/reference/datamodel.html#object。拉德

所以在你的情况下最简单的事情就是添加__radd__ = __add__

from decimal import Decimal

class MyType:
    def __init__(self, value):
        self.value = Decimal(str(value))
    def __repr__(self):
        return f'<MyType {self.value}>'

    def __add__(self, other):
        if not isinstance(other, MyType):
            other = MyType(other)
        return MyType(self.value + other.value) 

    __radd__ = __add__

推荐阅读