我一直在尝试使用python中的类将新的变量类型设置为四元数。 我已经知道如何让它添加一个整数或浮点,但我不知道如何让它添加一个四元数到浮点/整数。我只写了大约一个月的代码,试图学习如何编程来制作“不同数字系统的通用计算器”或UCFDN。我也在努力让它为uuu sub uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。有可能吗
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__
(和__radd__
)应该如下所示还要记住
__add__
和__radd__
看起来是一样的,因为加法是可交换的。但是__sub__
和__rsub__
看起来会不同,因为在__rsub__
中,self
是减法操作的右侧和顺序问题相关问题 更多 >
编程相关推荐