【问题标题】:How do you change what can be added to an integer in python?你如何改变python中可以添加到整数的内容?
【发布时间】: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。但总的来说,如果您无法处理某些事情,则应该提出异常,而不是强制退出。前者可以由调用者处理,即使不处理,也可以提供堆栈跟踪和错误消息,以便更好地调试使用。

标签: python class add


【解决方案1】:

如果__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 是减法运算的右手侧,并且顺序很重要。

【讨论】:

    猜你喜欢
    • 2021-09-09
    • 2013-06-22
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多