Lecture 28

Protocols

MCS 260 Fall 2021
David Dumas

Reminders

• Work on Project 3. Do not delay!
• We'll talk about Project 3 a bit today.
• 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   (only available if mutable)
• for item in seq:

Custom sequence

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

• __len__()
• The return value determines len(obj)
• __getitem__(idx)
• The return value determines obj[idx]

These methods form the sequence protocol.

Item assignment

To make a sequence mutable, add one more method:

• __setitem__(idx,val)
• Will be called when obj[idx]=val is executed
codebecomes
obj[1]obj.__getitem__(1)
obj[1]=60obj.__setitem__(1,60)
len(obj)obj.__len__()
for x in obj:   # stufffor 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 FGS to represent a finite geometric sequence.

We'll keep track of start, ratio, and length.

Indexing will be used to request an item from the sequence, which will be computed when needed but not stored.

Item assignment

Let's support item assignment with __setitem__.

• Assigning index 0 changes start
• Assigning any other index keeps start the same but adjusts ratio
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 1, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.5964744091033936, "perplexity": 8155.179457778887}, "config": {"markdown_headings": false, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.3, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2022-27/segments/1656103984681.57/warc/CC-MAIN-20220702040603-20220702070603-00356.warc.gz"}