Week 6: Object Oriented Programming and Graphics

Class Recordings

To access recordings, sign in to YouTube with your @swarthmore.edu account.

Monday Wednesday Friday

Announcements

  • Lab 5 available now, due Saturday night.

  • Run handin21 and submit lab early if you are leaving early for break.

  • No Ninja session Friday night.

Week 6 Topics

  • Classes and Objects

  • Object oriented programming

  • methods vs functions

  • Graphics as objects

  • Animation

  • Fall break

Monday

Object Oriented Programming (OOP)

This week, we introduce a new style of programming called object-oriented programming (OOP). OOP is in contrast to the imperative style that we previously used, where functions and data are defined separately. In OOP, we introduce the concept of objects which are defined by:

  • The data they hold (what they know)

  • The methods they can perform (what they can do)

Objects are pre-defined in terms of what type of data and methods they have. This is part of the class definition (we will do this later in the semester). Classes are the data type (like str and list - both types of objects). Objects are instances of a class. For example:

lst1 = list()
nums = [2, 5, 6]

Both lst and nums are objects of the class list. They hold data and have methods that can be called on them e.g., append(), extend(), etc.

nums.append(10)
nums.extend([15, 20, 25])

To use objects, you need to first create the object. This is known as initializing or calling the constructor of the object. The constructor is a function that has the same name as the class type (list(), str()). Second, you call methods on the object. Methods are similar to functions in that they can accept input parameters and return values. Each method however is part of a specific class and must be called on a particular object or instance of that class using the dot notation <objectName>.<methodName>

"Function" vs. "Method"

While similar, the words function and method are subtly different.

  • A function is an independent sequence of instructions that your program can call on input(s) to produce an output. To call a function, just specify the name of the function and pass in arguments in parentheses.

    lst = [1, 2, 3]
    final = get_last(lst)   # Assumes the user has written this function.
  • A method is associated with a particular class (e.g., strings or lists) and implicitly operates on an instance objects of that type. To call a method, first specify the object to call it on, followed by a . and the name of the method and any arguments in parentheses.

    lst = [1, 2, 3]
    final = lst.pop()       # The 'pop' method is built-in to Python's list type.

There are generally two types of methods:

  • getters - methods that retrieve data from the object

  • setters - methods that change the data in the object

Some methods do a combination of both (both change and retrieve information).

You can use the help function in python to get a list of methods for a particular class and some occasionally useful documentation. Just specify the name of a class or the name of an object in the parentheses of help. For some of the built-in types like str and list the documentation and methods may cover features we do not cover in CS21. Do no worry about knowing all of these methods. If we need a particular one in the course, we will say more about it.

$ python3
>>> help(str)
>>> help(list)

Note that isdigit() is a str method. In lab 03, before you knew object oriented design and method syntax, we gave you an isdigit() function that took a string parameter as input. But now you can just call s.isdigit() on a string to get the same result.

Graphics Library

We’ll use a graphics library to help understand objects. Note that we are using a special (simplified) graphics library; refer to the documentation as well as links on the syllabus for the capabilities of the library as well as download instructions if you want to use it on your laptop.

Example programs:

Moo
Starry Night

The key elements for using the library are:

  1. Import the library. The * in this context imports all the classes and functions from the library. This is useful shortcut when we will be using most of the features in a library.

    from graphics import *
  2. In your program, create a GraphWin object — the graphics window where we’ll draw things.

    win = GraphWin("Title", 800, 800)
  3. Create whatever shapes you want. For example, a point:

    pt = Point(200, 120)
  4. Draw shapes in the window

    pt.draw(win)
  5. To prevent the program from closing, use the method getMouse() that waits for a user to click the mouse before continuing/closing

    win.getMouse()      # Returns the coordinates of the click.

Playground

The playGround.py contains a small sample graphics program. Let’s test out new things in here to get a feel for the graphics library.

On your own, spend a few minutes modifying the program and seeing the changes. In particular try the following:

  • Create a window that is wider than it is tall.

  • Add a few shapes to the window in different spots. Use the documentation to learn about new shapes and how to customize them.

  • Be sure to change the colors of at least one shape.

Wednesday

Colors

The library supports many named colors. If you want to see the available colors, use the color picker library:

$ python3
>>>from colorPicker import colorPicker
>>>colorPicker()

This will popup a swatch of colors; click on the color and the name will be printed to the terminal. You can use the name in setFill() etc. to set the color.

Another option is to use a numeric value. One way to describe a color is the RGB standard - how much red, green, and blue there is in the color. This comes from television displays and monitors; a pixel on your screen is a combination of a red light, green light, and blue light mixed together. Each color can be described as an integer between 0 and 255 with 0 being e.g., "no red" and 255 being "full red". Here is how you can get the color corresponding to 200 red, 200 green, and 0 blue.

color_rgb(200,200,0)

To use this value, give it to setFill()

circ = Circle(Point(50,50),25)
circ.setFill(color_rgb(200,200,0))

Animation and Moving

In animate.py, we’ll write a program that animates a circle across the screen. This will require the use of three ideas:

  1. getMouse() method for GraphWin to get the location of where the user clicked

  2. move() method for all shapes to change the current location of a drawn object

  3. sleep() in the time library to create pauses in the code so that the movements don’t occur too fast.

Friday

Memory Diagrams/Stack Traces for Objects

We will continue to use stack diagrams to trace through programs and understand how they work. This is an essential skill to being able to think computationally and write effective programs. In duplicate.py, we have a program that wants to create two circles, one red and one green, of the same size. The program does not work; work with a partner and trace through the program to see why.

Grid Coordinates: Tic-Tac-Toe Example

You may have noticed that the default coordinate system for the graphics library is a bit odd — it treats the top left corner as (0, 0), and positive offsets move to the right (x direction) and down (y direction). Since this format is different from what you’re likely used to from math courses, it probably feels unnatural. Fortunately, the graphics library gives us a way to change it: a window object has a setCoords() method.

The setCoords() method lets you redefine the number associated with the lower left and upper right corners of a graphics window. This is useful for two reasons:

  1. It lets you redefine the lower left corner to be (0, 0), which better matches intuition.

  2. It lets you redefine how the window is divided into a grid, which for some problems, makes it easier to reason about shape placement.

For example, consider a tic tac toe game board (3 x 3 grid). If you window dimensions aren’t divisible by 3, it would be a pain to divide it up into a 3x3 grid. The setCoords() method allows you redefine the window into exactly what you want — a 3x3 window.

Let’s walk through an example in tictactoe.py.

Functions and Objects

Objects interact with functions in same way as basic types (ints, floats, strings, and lists). This means that we can return graphics objects we create and also send them in as arguments/parameters.

Exercise: create rectangles and find the tallest

In createRectangles.py, we have a partially completed program. The end goal is to write a program that allows the user to draw rectangles of various sizes, finds the tallest one, and colors it in.

Complete the task in this order:

  1. Pair up and explain each line of the program as is. Ask a ninja if you are not sure what a part of the program is doing.

  2. Write a function to give a color to a rectangle, and call that function from main to change the rectangle’s color.

  3. Change the main function of the program to create multiple rectangles (e.g., 3), and save them in a list.

  4. Lastly, write a function to find the tallest rectangle and return it. In main, change the code to only color the tallest rectangle.