CS21 Week 7: Object Oriented Programming and Graphics
Week 7 Topics
-
Classes and Objects
-
Object oriented programming
-
methods vs functions
-
Graphics as objects
-
Animation
-
Spring 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)
Every object is par of a class which defines the type of data and methods each
object will have. Classes allow us to define new data types. This week, we will be
using existing classes in python to create and use objects. Near the end of the semester
we will write our own classes. Objects are instances of a class. Two of the basic types
we have seen so far, are really classes: str
and list
. When we create a string variable,
or a list variable, we are creating objects, or instances of the corresponding class type.
lst1 = list()
nums = [2, 5, 6]
Both lst
and nums
are objects of the class list
.
Previously, we passed lists and strings to functions to manipulate or process these objects,
but objects and classes also have methods that are part of the class. A method is
a function inside a class. We can call a method, by specifying the name of the object, a dot,
and the name of the method. Two example methods in the list
class are append()
, and
extend()
.
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 can call methods on the object. Methods are similar to functions in
that they can accept input parameters and can 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.
|
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 not worry about knowing all of these
methods. If we need a particular one in the course, we’ll tell you more about
it.
$ python3
>>> help(str)
>>> help(list)
You can skip over methods beginning with a double underscore __
. Some helpful string methods are:
-
isalpha()
: Return True if the string is an alphabetic string -
isdigit()
: Return True if all characters in the string are digits -
isspace()
: Return True if all characters in the string are whitespace -
join(lst)
: Concatenate/join a list of strings using the given string as a delimiter -
split(sep)
: Split a string into a list of strings separated by a delimiter -
strip()
: Remove leading and trailing whitespace from a string -
lower()
: Convert a string to all lowecase
Some helpful string methods are:
-
append(item)
: Additem
to list -
clear()
: remove all items from a list (make list empty) -
count(value)
: count the number of occurrences ofvalue
in list -
reverse()
: reverse list in place, modifying list -
sort()
: sort list in place, modifying list
Graphics Library
We’ll use a graphics library to help understand objects, and rapidly expand the number of classes/types we will know about. 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.
Example programs:
The key elements for using the library are:
-
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 *
-
In your program, create a
GraphWin
object — the graphics window where we’ll draw things.win = GraphWin("Title", 800, 800)
-
Create whatever shapes you want. For example, a point:
pt = Point(200, 120)
-
Draw shapes in the window
pt.draw(win)
-
To prevent the program from closing, use the method
getMouse()
that waits for a user to click the mouse before continuing/closingwin.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))
Cloning and Aliasing
In duplicate.py
, we attempt to draw two similar circles. We start by creating a small blue circle and then pause to get a mouse click from the user.
Next we try to create a second circle using the syntax circ2 = circ
and modifying circ2
. This does not have the desired effect. Sketch a stack
diagram to determine what is happening.
What happens if we replace circ2 = circ
with circ2 = circ.clone()
. What do you think the clone()
method does? clone()
is a method common to
each graphics shape primitive, e.g., Circle
, Point
, Line
, Rectangle
.
Shapes and Lists
In createRectangles.py
we wrote a createRectangle
function that instructs the user to
click two points and then draws a rectangle having those two points as opposite corners. It also
returns the created Rectangle
object.
In main
, modify your program to first create an empty list. Use a loop to create three rectangles.
Use append()
to add each rectangle to a list.
Write a function called colorRectangle
that has one parameter, a rectangle object to color. Your function
should set the fill and outline of the rectangle to a color of your choosing. Modify main again to color
the first rectangle.
Finally write a function called getTallest
with one parameter, a list of rectangles. It should find and
return the tallest rectangle in the list. You should use the getHeight()
function to compute the height
of each rectangle in the list. Modify main one last time to call getTallest
, and color only the tallest rectangle.
Friday
Nested loops
We first learned about for
loops, if
statements, and while
loops independently. But these coding features can be combined in multiple ways.
One common way is the nested loop, or a loop inside a loop. See the file nested.py
for some examples.
Note the following:
-
the indented inner loop must finish all of it’s iterations before the outer loop advances
-
the two loops have different loop variable names. You can use both loop variable names in the inner loop, but only the outer loop variable in the outer loop.
Setting Coordinates
By default, the upper left of a GraphWin
object has coordinates \(x,y=(0,0)\) and the lower right has coordinates \((w,h)\).
This is often an inconvenient system of measurement. The setCoords(left, bottom, right, top)
method allows you to define a new coordinate
system by specifying the left, bottom, right, and top boundaries, respectively. For example, win.setCoords(0,0,10,10)
would set the lower left
of the window to have lower left coordinates (0,0) and and upper right coordinates (10,10). The setcoords.py
file shows a more complex demo
where we wish to draw a sine curve over the domain \(-\pi\) to \(\pi\) (in radians). The sin(x)
function has range of -1 to 1. We use
setCoords
to set the desired dimensions and plot the coordinates (x, sin(x))
as a series of points.
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:
-
getMouse()
method forGraphWin
to get the location of where the user clicked -
move()
method for all shapes to change the current location of a drawn object -
sleep()
in thetime
library to create pauses in the code so that the movements don’t occur too fast.