Learn Object Oriented Programming by re-implementing Python’s Complex class: Part-4

leangaurav
Industrial Python
Published in
2 min readSep 13, 2019

The built-in complex class is named complex with the small ‘c’. We will also name our class Complex but with the capital ‘C’.

For now we have only __init__ and __str__ methods. This allows us to create Complex objects and easy printing. Notice that the init has default arguments as well. Following are some good ways to create Complex objects.

Now we will start adding magic methods for some operators to Complex.

Addition and Subtraction

We first add simple ones : __add__ for + and __sub__ for -.

That was quite simple to understand I guess. The entire list of all magic methods for all operators is here.

For all binary operators, the magic method needs to take 2 arguments the first one being self.

A call to c1 + c2 translates to something like this.

c1.__add__(c2)

or

Complex.__add__(c1, c2)

So the operand before the operator goes into self and the one after goes as argument to other

Conjugate and Negation

Minus operator can be used as both binary and unary. We have already seen the binary version is implemented by overloading the __sub__ magic method.

Python provides __neg__ for unary version. But for conjugate, there is no operator. So we will define conjugate as a method conjugate in the class. Both of these will take only one argument self.

Multiplication and Division

Lets implement the only two remaining methods: __mul__ and __truediv__.

Notice that name is __truediv__ for normal division and __floordiv__ for int division or // operator.

That was our last piece of code in the Complex series.Find the jupyter notebook with complete code here.

Prev: Complex Numbers 3: Reinvent Python’s complex class

--

--

leangaurav
Industrial Python

Engineer | Trainer | writes about Practical Software Engineering | Find me on linkedin.com/in/leangaurav | Discuss anything topmate.io/leangaurav