Lecture 4

Object-oriented Programming

Operator overloading

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Overloading

Adding special methods lets a custom class work with built-in operations like +, *, len, abs, ...

These methods get called automatically when we apply addition, multiplication, etc., to instances.

Some special methods

OperationSpecial method
A==BA.__eq__(B)
A+BA.__add__(B)
A-BA.__sub__(B)
A*BA.__mul__(B)
A/BA.__truediv__(B)
A**BA.__pow__(B)

List of many more in the Python documentation.

More special methods

OperationSpecial method
str(A)A.__str__()
len(A)A.__len__()
abs(A)A.__abs__()
bool(A)A.__bool__()
A[k]A.__getitem__(k)
A[k]=vA.__setitem__(k,v)

Our main example

  • Point2 — point in the plane (a location in 2D)
  • Vector2 — vector in the plane (e.g. the displacement between two points)

This is all going in an example module oop/plane.py in the course code repo.

Supported operations

Language features used

  • isinstance(obj,classname) -- returns bool indicating whether obj is an instance of the named class (or subclass thereof)
  • NotImplemented -- Special value that operators should return if the operation is not supported

__add__ & __radd__

In evaluating A+B, Python first tries

A.__add__(B)
but if that fails (returns NotImplemented), it will try
B.__radd__(A)

There are "reflected" versions of all the binary operations (e.g. __rmul__).

Overloading danger

Overloading is best used when a function or operator has a clear, natural meaning for a class.

If used too much or in unintuitive ways, it makes programs harder to understand.

Singletons

When a class is designed so that it only ever has one instance, the class (or the only instance of it) is called a singleton.

We've seen two of these so far:

  • None, the only instance of NoneType
  • NotImplemented, the only instance of NotImplementedType

References

  • I discussed overloading in MCS 260 Fall 2021 Lecture 26.
  • See Lutz, Chapter 30 for more information about overloading.
  • Lutz, Chapters 26-32 discuss object-oriented programming.

Revision history

  • 2023-01-23 Finalization of the 2023 lecture this was based on.
  • 2024-01-16 Initial publication.