'Python unsupported operand type TypeError:

I have been messing around with object instantiation. I don't understand why this is raising errors while returning its identity?

   >>> class Complex:
    ...     def __init__(self):
    ...         print(f'Complex identity: {id(self)}' )
    ...

>>> a = Complex() * 27
Complex identity: 2660854434064
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Complex' and 'int'


Solution 1:[1]

You create an instance of a class and trying to multiply the instance with a number ,You want to do overloading of operations,see an example below how to do it the proper way with Points(You can adjust it to what you want to do with Complex number

class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return "<Point x:{0},y:{1}>".format(self.x, self.y)

    # implement addition
    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)

    # implement subtraction
    def __sub__(self, other):
        return Point(self.x - other.x, self.y - other.y)

    # implement in-place addition
    def __iadd__(self, other):
        self.x += other.x
        self.y += other.y
        return self



    # Declare some points
    p1 = Point(10, 20)
    p2 = Point(30, 30)
    print(p1, p2)

    # Add two points
    p3 = p1 + p2
    print(p3)

    # subtract two points
    p4 = p2 - p1
    print(p4)

    # Perform in-place addition
    p1 += p2
    print(p1)

Solution 2:[2]

In the specific instance of what you've done you haven't created the appropriate dunder methods for your class:

class Complex:
    def __init__(self, real, imaginary):
        print(f'Complex identity: {id(self)}')
        self.complex = f"{real} + {imaginary}i"
        self.real = real
        self.imaginary = imaginary

    def __mul__(self, input):
        if isinstance(input, int): #Just an example error type
            return f"{self.real*input} + {self.imaginary*input}i"
        else:
            raise Exception("TypeError: Not complex, real or imaginary")

if __name__ == "__main__":
    a = Complex(10,23)
    print(a*10)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nir Elbaz
Solution 2 Dharman