python - 你如何改变python中可以添加到整数的内容?
问题描述
我一直在尝试使用 python 中的类来创建一个四元数类型的新变量。我已经想出了如何让它添加一个整数或一个浮点数,但我不知道如何让它添加一个四元数到一个浮点数/整数。我只编写了大约一个月的代码,试图学习如何编写“用于不同数字系统的通用计算器”或 UCFDNS。我也在努力让它适用于 __sub__、__mul__、__div__。甚至可能吗?
class Quaternion:
def __init__(self, a, b, c, d):
self.real = a
self.imag1 = b
self.imag2 = c
self.imag3 = d
#addition
def __add__(self, other):
if type(other) == int or type(other) == float:
other1 = Quaternion(other,0,0,0)
return other1 + self
elif type(other)==type(self):
return Quaternion(other.real+self.real,other.imag1+self.imag1,other.imag2+self.imag2,other.imag3+self.imag3)
else:
print('You can'+"'"+'t add a',type(other),' with a QuaternionNumber')
import sys
sys.exit(1)
解决方案
如果不知道如何处理加法,正确的实现__add__
应该返回特殊常量。NotImplemented
所有 Python 内置类都是为了遵守这一点而编写的。如果__add__
返回NotImplemented
,则 Python 将__radd__
在右侧调用。所以你需要做的就是实现与你的类__radd__
基本相同的事情__add__
,你的类将神奇地开始使用内置类型。
请注意,为了尊重其他人做同样的事情,NotImplemented
如果你不能处理操作,你也应该返回,所以你的__add__
(and __radd__
) 应该看起来像
def __add__(self, other):
if type(other) == int or type(other) == float:
other1 = Quaternion(other,0,0,0)
return other1 + self
elif type(other)==type(self):
return ComplexNumber(other.real+self.real,other.imag1+self.imag1,other.imag2+self.imag2,other.imag3+self.imag3)
else:
return NotImplemented
还要记住,__add__
and__radd__
看起来是一样的,因为加法是可交换的。但是__sub__
,__rsub__
例如,看起来会有所不同,因为在 中__rsub__
,self
是减法运算的右侧,并且顺序很重要。
推荐阅读
- javascript - 我应该使用什么下拉菜单里面有很多元素?
- typescript - 如何在 Webpack 上避免重复的 sass 导入(使用 @use)
- c++ - 如何将 c 样式的字符串或字符串文字附加到 std::vector
? - python-3.6 - 如何将 TensorFlow 对象检测 API 模型转换为 TFLite?
- java - java中的正偶数代码帮助(Uncaught SyntaxError: Unexpected identifier",)
- javascript - React Native - Mobx 如何使用远程数据初始化存储
- elasticsearch - 如何在 Kibana 中为字段创建值列表?
- reactjs - 如何将此创建商店与 thunk 转换为基于承诺的?
- jsf - SelectOneRadio 总是返回 0
- react-native - 在 RecyclerListView 中的屏幕视图外在反应本机时暂停视频