python - 你如何在 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'
解决方案
在 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__
推荐阅读
- sql-server - 从字符串转换为唯一标识符时转换失败 - 不回滚事务
- android - Android 应用,通过 BLE 模块接收微控制器通过 UART 发送的数据
- angular - Angular 6:刷新后从localStorage获取令牌
- spring - 如何在 Spring Boot RestTemplate 中将正文内容作为原始 JSON 而不是表单数据发送
- ios - 如何在 Swift 中创建一个优雅的保护/返回语句来提供输出?
- javascript - 使用 Jsom 插入查找字段的共享点
- c# - 在 MongoDb 中执行 UpdateAsync
- r - 使用 data.table 在单个条件下替换多个列
- botframework - Microsoft Teams:获取用户的时区?
- spring - 真的有必要将 Hystrix 与反应式 Spring Boot 2 应用程序一起使用吗?