Lecture 3

End of tour, start of OOP

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 3: End of tour, start of OOP

Reminders and announcements:

  • Read the syllabus.
  • Homework 1 posted. Due Noon on Wed 17 January.
    • Work individually
    • Assignment lists the online resources you can use.
  • No class on Monday (MLK holiday).

Files

open(filename,mode,...) opens a file and returns a file object. Mode string selects reading ("r"), writing ("w"), ...

Methods of the file object perform input/output (I/O).

Read/write strings to text files (default), bytes to binary files (add "b" in mode).

.close() a file when finished.

The basics are in Lutz, Chapter 9 and MCS 260 Lec 13 and Lec 14.

Functions

Named, reusable code blocks you can call (run) from elsewhere in your code.

def contains_all_digits(x):
    s = str(x) # decimal rep of x as a string
    for c in "0123456789":
        if c not in s:
            return False
    return True
Interactive use:

>>> contains_all_digits(2*5)
False
>>> contains_all_digits(2**94)
True

See Lutz, Chapters 16-18 or MCS 260 Lec 9 and Lec 24.

Docstrings

The first non-comment statement in any Python function should be a string on a line by itself. That string should describe the function. It is called a docstring.


        def contains_all_digits(x):
            "Does decimal representation of `x` use all digits 0-9?"
            s = str(x) # decimal rep of x as a string
            for c in "0123456789":
                if c not in s:
                    return False
            return True
        

Docstrings can also appear as the first statement in a file or in a class definiton.

Use comments, not strings, in all other cases!

Modules

A module keeps a bunch of related code in one place; good for reuse and organization. The statement

import modulename

will look for modulename.py in current directory, or a built-in module with that name, and make its functions, classes, etc. available.

Use modulename.funcname(...) to call a function in a module.

See Lutz, Chapters 22-23 or MCS 260 Lec 20.

Classes

Classes let you define custom types in Python with attributes (data) and methods (behavior).


        class Point2:
            """A point in the xy-plane"""  # <--- Remember docstring!
            def __init__(self,x,y):
                """Initialize new point instance"""
                self.x = x   # make a new attribute (self.x)
                self.y = y   # make a new attribute (self.y)
            def translate(self,dx,dy):
                """Move the point by a vector (dx,dy)"""
                self.x += dx
                self.y += dy

        p = Point2(1,2)  # calls __init__(...)
        p.translate(5,0)
        print("After moving, p.x is {}".format(p.x))  # will print 6
    

See Lutz, Chapters 27-28 and MCS 260 Lectures 25, 26, 27, 28.

(End of the tour)

Object-Oriented Programming

Now we'll start our unit on object-oriented programming (OOP).

We assume knowledge of: Class definitions, creating instances, accessing attributes, calling methods.

We DO NOT assume knowledge of: Subclasses, inheritance, operator overloading.

Class vs instance

  • class means the type, e.g. int or Point2
  • instance or object is a value belonging to a class, e.g. 24 or Point2(5,7)

Special methods / overloading

In Python, built-in operations are often silently translated into method calls.

e.g.   A+B turns into A.__add__(B)

These special method names begin and end with two underscores (__). They are used to customize the way your classes work with built-in language features.

Using these to add special behavior for operators like +,-,* is called operator overloading.

Operator examples

ExpressionSpecial 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

ExpressionActually calls
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)

Live coding

Let's work on

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

Difference of two Point2s is a Vector2.

Can multiply a Vector2 by a float or add it to a Point2.

Point2 plus Vector2 is a Point2.

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

References

  • The Python tour is an expanded version of the notebooks created in lecture this week.
  • Individual slides refer to chapters from Lutz (Learning Python 5ed).
    • Free access to online book for UIC students; see course web page.
  • The MCS 260 Fall 2021 home page has slide presentations, sample code, and other resources for review.

Revision history

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