1

I'm creating my own complex number class (not using Python's built in one) and I'm running into a problem when I try to add zero to my complex number. For reference this is the error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "display.py", line 25, in __init__
t.color(mandelbrot(c).getColor())
File "C:\Users\Joe\Desktop\Python\mandelbrot.py", line 10, in __init__
z = z*z + self.__starting_value
TypeError: unsupported operand type(s) for +: 'int' and 'complex'

Where self.__starting_value is the complex number.

The addition definition goes as follows:

class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        return complex(self.__real + other.__real, self.__imag + other.__imag)

The solution should be simple enough but I am still learning Python and could use the help.

L3viathan
  • 26,748
  • 2
  • 58
  • 81
yojo890
  • 13
  • 3

3 Answers3

0

int + complex will first try to useint.__add__. complex + int will first try to use complex.__add__.

You need to implement complex.__radd__. See the related note in Emulating numeric types:

These functions are only called if the left operand does not support the corresponding operation and the operands are of different types.

You will need to handle the case where other is int in both complex.__add__ and complex.__radd__.

Galen
  • 1,307
  • 8
  • 15
0

__add__ is for addition when the left-hand-side operand is of the type you're writing. When Python fails to call the int __add__ method, it tries __radd__. If you define __radd__ (with the same behavior), you'll get the result you want.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

Two problems:

  1. You are only handling addition of a complex object to a complex object, when you want to also be able to handle complex object + int.

  2. When adding in this order (int + custom type), you need to add a reflected addition method (__radd__)


class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        if isinstance(other, complex):
            return complex(self.__real + other.__real, self.__imag + other.__imag)
        else:
            return complex(self.__real + other, self.__imag)
    def __radd__(self, other):
        return self + other

N.B.: It is considered bad style to shadow built-in names (like complex).

L3viathan
  • 26,748
  • 2
  • 58
  • 81