June 2001
Intermediate to advanced
416 pages
10h 24m
English
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.
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, ... |
Read now
Unlock full access