Linux/Unix > Python Essential Reference, Second Edition > 7. Classes and Object-Oriented Programming > Operator Overloading | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105087128014158189098045

### 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, self.imag + other.imag)
        # self - other
        def _ _sub_ _(self,other):
            return Complex(self.real - other.real, self.imag - other.imag)
        # -self
        def _ _neg_ _(self):
            return Complex(-self.real, -self.imag)
        # other + self
        def _ _radd_ _(self,other):
            return Complex._ _add_ _(other,self)
        # other - self
        def _ _rsub_ _(self,other):
            return Complex._ _sub_ _(other,self)
        # Coerce other numerical types to complex
        def _ _coerce_ _(self,other):
            if isinstance(other,Complex):
                return self,other
            try:   # See if it can be converted to float
                return self, Complex(float(other))
            except ValueError:
                pass

In this example, there are a few items of interest:

- First, the normal behavior of `_ _repr_ _()` is to create a string that can be evaluated to re-create the object. In this case, a string of the form `"Complex(r,i)"` is created. On the other hand, the `_ _str_ _()` method creates a string that’s intended for nice output formatting (this is the string that would be produced by the `print` statement).

- Second, to handle operators in which complex numbers appear on both the left and right side of operators, both the `_ _op_ _()` and `_ _rop_ _()` methods for each operation must be provided.

- Finally, the `_ _coerce_ _` method is used to handle operations involving mixed types. In this case, other numeric types are converted to complex numbers so that they can be used in the complex arithmetic methods.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.