Lecture 26

Object-oriented Programming 4

Protocols

MCS 260 Fall 2020
David Dumas

Reminders

  • Work on Project 3 ASAP. Do not delay!
  • Quiz 9 due Monday at 6pm Central
  • Worksheet 9 solutions posted
  • Goals

    • Introduce the sequence protocol for Python classes
    • Work on an example
    • Discuss other Python protocols
    • All of this is Python-specific. Some other languages use the term interface for a similar concept, though the details differ quite a bit.

      What is a sequence?

      In Python, a sequence is an ordered container supporting access to its items by 0-based index.

      Things you can do with a sequence seq:

      • len(seq)
      • seq[3]
      • seq[3] = val
      • for item in seq:

      Custom sequence

      If you create a class with the following methods, it can be used as a mutable sequence:

      • __len__() — returns the length
      • __getitem__(idx) — returns item at given index
      • __setitem__(idx,val) — set item at given index

      These methods form the (mutable) sequence protocol.

      codebecomes
      obj[1]obj.__getitem__(1)
      obj[1]=60obj.__setitem__(1,60)
      len(obj)obj.__len__()
      for x in obj:
        # stuff
      for i in range(len(obj)):
          x = obj[i]
          # stuff

      Geometric sequence

      A geometric sequence (or geometric progression) is a sequence of numbers where the ratio between neighboring terms is constant.

      Infinite example: $1,2,4,8,16,32,64,\ldots$

      Finite example: $5,15,45,135,405$

      Non-example: $6,8,10,12,14$

      Geometric sequence class

      Let's make a class FiniteGeometricSequence that will represent a finite geometric sequence.

      We'll keep track of start, ratio, and length, but will only compute terms when requested.

      Item assignment

      Let's support item assignment with __setitem__.

      Adopt these conventions:

      • Assigning index 0 changes start
      • Assigning any other index keeps start the same but adjusts ratio

      Other protocols

      Still more can be found in the collections.abc module, which contains classes you can subclass when implementing the protocols.

      References

      Revision history

      • 2020-10-22 Initial publication