Home Adding zero to my complex number class
Reply: 3

Adding zero to my complex number class

yojo890
1#
yojo890 Published in 2017-12-06 20:51:17Z

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
2#
L3viathan Reply to 2017-12-06 21:36:24Z

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).

Galen
3#
Galen Reply to 2017-12-06 21:35:10Z

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__.

Silvio Mayolo
4#
Silvio Mayolo Reply to 2017-12-06 21:35:47Z

__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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308614 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO