在python中,如何更改可以添加到整数中的内容?

2024-10-17 06:13:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试使用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)

Tags: selfaddreturndeftypesys整数real
1条回答
网友
1楼 · 发布于 2024-10-17 06:13:38

如果__add__的正确实现不知道如何处理加法,则应返回特殊常量NotImplemented。所有Python内置类的编写都遵循这一点。如果__add__返回NotImplemented,Python将调用右侧的__radd__。因此,您所需要做的就是实现__radd__来做与__add__基本相同的事情,您的类将神奇地开始使用内置类型

注意,为了尊重做同样事情的其他人,如果您不能处理该操作,您还应该返回NotImplemented,因此您的__add__(和__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____radd__看起来是一样的,因为加法是可交换的。但是__sub____rsub__看起来会不同,因为在__rsub__中,self是减法操作的右侧和顺序问题

相关问题 更多 >