Home > other >  How do you change what can be added to an integer in python?
How do you change what can be added to an integer in python?

Time:09-17

I've been trying to use classes in python to make a new variable type a Quaternion Number. I've figured out how to make it add an integer or a float to it, but I can't figure out how to make it add a Quaternion to a float/integer. I've only been coding for about a month trying to learn how to program to make a "Universal Calculator For Different Number Systems" or UCFDNS. I'm also trying to make it work for __sub__, __mul__, __div__. Is it even possible?

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)

CodePudding user response:

A correct implementation of __add__ should return the special constant NotImplemented if it doesn't know how to handle the addition. All Python built-in classes are written to comply with this. If __add__ returns NotImplemented then Python will call __radd__ on the right-hand side. So all you need to do is implement __radd__ to do basically the same thing as __add__ and your class will magically start working with built-in types.

Note that, in order to be respectful of other people doing the same thing, you should also return NotImplemented if you can't handle the operation, so your __add__ (and __radd__) should look like

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

Also keep in mind that __add__ and __radd__ will look the same, since addition is commutative. But __sub__ and __rsub__, for instance, will look different, because in __rsub__, self is the right-hand side of the subtraction operation and order matters.

  • Related