【发布时间】:2021-09-11 01:20:04
【问题描述】:
我一直在尝试使用 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)
【问题讨论】:
-
你自己滚动是有原因的吗? Python 有一个内置的复杂类型。
-
@blorgon 是吗?我该如何使用它?
-
@blorgon 它有四元数或其他数字系统的东西吗?
-
作为更一般的说明,
sys.exit(1)从来都不是库中错误处理的好方法。在这种特殊情况下(根据我的回答),您应该返回NotImplemented。但总的来说,如果您无法处理某些事情,则应该提出异常,而不是强制退出。前者可以由调用者处理,即使不处理,也可以提供堆栈跟踪和错误消息,以便更好地调试使用。