首页 > 解决方案 > 你如何改变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)

标签: pythonclassadd

解决方案


如果不知道如何处理加法,正确的实现__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是减法运算的右侧,并且顺序很重要。


推荐阅读