Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Operator Overloading

Program gif illustrates operator overloading in Python. Operator overloading   allows the programmer to use the built-in operators for user-defined types.

Program: Complex class __add__, __sub__ and __mul__ methods.

To overload the built-in +, - and * operators so that they may be used with Complex operands, we define the methods called __add__, __sub__ and __mul__ (respectively). Given Complex variables c, d and e, the expression

c + d * e
is equivalent to
Complex.__add__(c, Complex.__mul__(d, e))

next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.