CS 115 Lab 13 Setup and Practice

[Back to lab instructions]

Refer to the Week 14 reading or other resources as necessary to complete this assignment.


Setup

  1. If the machine was on when you started using it, reboot it to MacOS.
  2. Follow these procedures to mount your blue home-directory on the local machine and create a PyCharm project (call it Lab13). You will use PyCharm in the next part, but, it is important that you set up your project now so that if you run into any issue, we can resolve them quickly.
  3. Right-click or control-click to download these 2 files into your default Python directory (C:\Python34 on Windows or Documents on a Mac):

 

Background recap

Object-oriented programming is all about defining our own data types and the operations they support. However, there are some limitations! Consider the code:

print(5)
Python knows exactly how to print this integer. More precisely, it knows how to internally convert that integer into its string representation, and then print that.

However, if you were to write something like:

s = Student('Example McStudent', [90, 100, 95]) # using the Student class from Lab 12, Part B
print(s)
...how is Python supposed to know how you would like this printed? It doesn't know anything about the Student data type beyond what you've provided in the class definition. In Part B of Lab 12, we got around this by defining our own print method for the class, so we could do s.print() to print the student in exactly the format we desired. In Lab 13, we'll solve this problem differently: by defining a special method of our class that will cooperate with Python's provided print function.

Printing isn't the only problem! Again, with Python's provided data types, Python knows exactly what to do with something like

if 100 > 87:
or

if 'Los Angeles' < 'San Diego'
because it knows how to compare integers and strings. But if what if you tried to compare two Student objects? Python will throw up its hands: how is it supposed to know what makes one student "less than" another? In Lab 13, we'll define another special method that tells Python how the < operator works if it's comparing two objects of our new class. There are similar methods for other operators, but we won't cover those in this lab.