10.10 Operator Overloading

  • Can use operator overloading to define how Python’s operators should handle objects of your own types
  • Can overload most operators
  • For every overloadable operator, class object defines a special method
    • e.g., __add__ for addition (+) or __mul__ for multiplication (*)
  • Overriding these methods enables you to define how a given operator works for objects of your custom class
  • Complete list of special methods

    https://docs.python.org/3/reference/datamodel.html#special-method-names

Operator Overloading Restrictions

  • Precedence cannot be changed by overloading
  • Left-to-right or right-to-left grouping of an operator cannot be changed
  • “Arity” of an operator—whether it’s unary or binary—cannot be changed
  • Cannot create new operators
  • How an operator works on objects of built-in types cannot be changed
  • Works only with objects of custom classes or with a mixture of an object of a custom class and an object of a built-in type

Complex Numbers

  • We’ll define a class named Complex that represents complex numbers
  • Complex numbers, like –3 + 4i and 6.2 – 11.73i, have the form
    realPart `+` imaginaryPart `* i`
    
  • i is the square root of -1
  • We'll overload + and +=

10.10.1 Test-Driving Class Complex

In [1]:
from complexnumber import Complex
  • Create and display a couple of Complex objects
In [2]:
x = Complex(real=2, imaginary=4)
In [3]:
x
Out[3]:
(2 + 4i)
In [4]:
y = Complex(real=5, imaginary=-1)
In [5]:
y
Out[5]:
(5 - 1i)
  • Use the + operator to add the Complex objects x and y
  • Adds the real parts of the two operands and the imaginary parts of the two operands, then returns a new Complex object
In [6]:
x + y
Out[6]:
(7 + 3i)
  • + does not modify either of its operands
In [7]:
x
Out[7]:
(2 + 4i)
In [8]:
y
Out[8]:
(5 - 1i)
  • Use += to add y to x and store the result in x
  • += operator modifies its left operand
In [9]:
x += y
In [10]:
x
Out[10]:
(7 + 3i)
In [11]:
y
Out[11]:
(5 - 1i)

10.10.2 Class Complex Definition

Method __init__

  • Initializes the real and imaginary data attributes
# complexnumber.py
"""Complex class with overloaded operators."""

class Complex:
    """Complex class that represents a complex number 
    with real and imaginary parts."""

    def __init__(self, real, imaginary):
        """Initialize Complex class's attributes."""
        self.real = real
        self.imaginary = imaginary

Overloaded + Operator

  • Overridden special method __add__ defines how to overload the + operator
def __add__(self, right):
        """Overrides the + operator."""
        return Complex(self.real + right.real, 
                       self.imaginary + right.imaginary)
  • Methods that overload binary operators must provide two parameters
    • the first (self) is the left operand
    • the second (right) is the right operand
  • We do not modify the contents of either of the original operands
    • Matches our intuitive sense of how this operator should behave

Overloaded += Augmented Assignment

  • Override special method __iadd__ to define how += adds two Complex objects
def __iadd__(self, right):
        """Overrides the += operator."""
        self.real += right.real
        self.imaginary += right.imaginary
        return self
  • Augmented assignments modify their left operands, so method __iadd__ modifies the self object, which represents the left operand, then returns self

Method __repr__

def __repr__(self):
        """Return string representation for repr()."""
        return (f'({self.real} ' + 
                ('+' if self.imaginary >= 0 else '-') +
                f' {abs(self.imaginary)}i)')

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.