python - Python 重载运算符不能在表达式的“两侧”工作
问题描述
我正在实现一个Fraction
使用分数的类(尽管python为此提供了一个库),问题是,我可以__add__
在分数和整数之间使用(+)运算符,但我不能__add__
在整数和整数之间使用一小部分。当表达式的顺序改变时,我得到一个错误。
>>> a = Fraction(1, 2)
>>> a + 1
Fraction(numerator=3.0, denominator=2)
>>> 1 + a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'Fraction'
>>>
有没有办法使这种表达方式1 + Fraction(1, 2)
起作用?也许类的左__add__
运算符Fraction
?
解决方案
只需实现radd
镜像添加。
class Fraction:
def __init__(self, value):
self.value = value
def __add__(self, other):
return Fraction(self.value+other)
def __radd__(self, other):
return self.__add__(other)
if __name__ == "__main__":
print((Fraction(1)+1).value)
print((1+Fraction(1)).value)
推荐阅读
- sql-server - 当表没有更新时,有没有办法发送 SQL 邮件?
- wordpress - 为自定义帖子类型添加和创建多个元框
- python - 如何检查数据存储python中的Put操作是否成功
- java - 如何在泛型类中强制类型返回值?
- javascript - 如何使用 javascript 防止父级 onclick 对子级进行操作
- ios - @react-native-firebase/messaging 没有在真实的 ios 设备中获取设备令牌
- python - 从我有我的项目的当前 python 文件夹运行 chromedriver
- php - 使用密码散列更新当前密码
- javascript - 当我将一组对象提交到 Vuex 存储时,这些对象会丢失它们的一个属性
- wordpress - 切换到新 URL 后,某些 Wordpress 图像缩略图未显示