Operator Overloading

User-defined objects can be made to work with all of Python’s built-in operators by adding implementations of the special methods described in Chapter 3 to a class. For example, the class in Listing 7.2 implements the complex numbers with some of the standard mathematical operators and type coercion to allow complex numbers to be mixed with integers and floats.

Listing 7.2. Mathematical Operators and Type Coercion
 class Complex: def _ _init_ _(self,real,imag=0): self.real = float(real) self.imag = float(imag) def _ _repr_ _(self): return "Complex(%s,%s)" % (self.real, self.imag) def _ _str_ _(self): return "(%g+%gj)" % (self.real, self.imag) # self + other def _ _add_ _(self,other): return Complex(self.real + other.real, ...

Get Python Essential Reference, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.