Lecture 19 — Classes, Part 2

Overview

  • Review of classes
  • TimeOfDay class
  • Lab 4 revision
  • Techniques that we will see:
    • Calling class methods from within the class
    • Class objects storing other objects, such as lists
    • Lists of class objects

Review of Classes

We will use our Point2d class from Lecture 18 to review the following:

  • Attributes:
    • These store the data associated with each class instance.
    • They are usually defined inside the class to create a common set of attributes across all class instances.
  • Initialization: function __init__ called when the object is created.
    • Should assign initial values to all attributes
  • Methods
    • Each includes the object, often referred to as self, as the first argument.
    • Some change the object, some create new objects
  • Special methods start with two underscores. Python interprets their use in a variety of distinct ways:
    • __init__ is the initializer
    • __str__ is the string conversion function
    • __add__, __sub__, etc. become operators

TimeOfDay Class

  • Listed in the Lecture 18 notes, but we have not gotten to it yet.
  • Access information about hours, minutes and seconds
  • AM or PM
  • Convert to string
  • Addition of times
  • Difference between two times.
  • Many other methods.
  • Only attribute is the number of seconds since midnight.
    • This is not known to the code that uses the TimeOfDay class.
    • It is done for programming convenience, as we will discuss in lecture.
    • Example of encapsulation!

Exercises

We will work through the implementation details together during lecture. The skeleton implementation is:

::

“”” Class for storing time. Time is reported on a military (24 hour) clock

“”“

class Time(object):
def __init__(self, hr, min, sec):
pass
def convert(self):
pass
def __str__(self):
pass
def __add__(self, other):
pass
def __sub__(self, other):
pass
if __name__ == ‘__main__’:
pass

Larger Example — Restaurant Class

Recall Lab 4:

  • Read and parse input lines that look like:

    The Greek House|42.73|-73.69|27 3rd St+Troy, NY 12180|\
       http://www.yelp.com/biz/the-greek-house-troy|Greek|1|5|4|5|4|4|5|5|5|5|5|4
    
  • Find restaurants and print out information based on a user selection

  • Original implementation based on a list was awkward:

    • We had to remember the role of each index of the list — 0 was the name, 1 was the lattitude, etc.
  • New implementation here is based on a class

Start to a Solution, the Main Code

Let’s look at lec19_business_class.py

  • Will be posted on the course web site.
  • Main initializationFunction convert_input_to_restaurant
    • Parses a restaurant line
    • Creates and returns a restaurant object
  • Function build_restaurant_list
    • Opens the input file
    • Reads each line
    • Calls convert_input_to_restaurant, and appends the resulting restaurant to the back of a list
  • Main code:
    • Builds the restaurant list
    • Gets a restaurant number from the user and prints it.
    • Then ? - Not written yet. We can do whatever we want.

Exercises

Looking at the code that is in lec19_restaurant_exercise.py

  1. Outline the methods that must be in the Restaurant class, including the parameters that must be passed to each method.
    • Thus, the way we want to use the class is dictating how we write it.
  2. Implement the rest of the main code assuming these methods are implemented correctly.
  3. (A slightly different topic:) In several places throughout the code, restaurants and lists of restaurants are being copied or passed into functions. Why is this not a substantial waste of computation?

Turning to the Restaurant Class

Look at lec19_business_class.py

  • Again, this will be posted as well.
  • The exact set of methods is likely to be somewhat different from what you came up with for the exercises just completed.
  • The __init__ function specifies the attributes.
    • Others could be added, such as the average rating, but instead these are computed as needed by methods.
    • Importantly, each class object stores a list of ratings, illustrating the fact that classes can store data structures such as lists, sets, and dictionaries.
  • We will briefly go over the remaining functions during lecture.

Exercises

  1. Write the minscore and maxscore methods. These should return -1 if the list is empty.
  2. Add code to the end of lec19_business_class.py to test the functions you have added.

Discussion

  • What is not in the Restaurant class?
    • No input or line parsing. Often, we don’t want the class tied to the particular form of the input.
    • As an alternative, we could add a method for each of several different forms of input.
  • Often it is hard to make the decision about what should be inside and what should be outside the class.
    • For example, we could have a method that tells us if a restaurant is in a particular city, or we could write a different method that returns that name of the city and make the comparison outside the class.
  • The Restaurant object stores a list as an attribute
    • This is our first example where the attributes are more than just simple variables.
  • We could add an Address class:
    • Reuse for objects other than restaurants
    • Not needed in this (relatively) short example.
    • Without it we store the address as a string; this feels like an incomplete implementation.

Summary

  • Review of the main components of a Python class:
    • Attributes
    • Methods
    • Special methods with names starting and ending with __
      • Initializer method is most important
  • Important uses of Python classes that we have seen today:
    • Calling class methods from other class methods
    • Classes containing lists
    • Lists of class objects.
  • Design of Python classes
    • Start by outlining how they are to be used
    • Leads to design of methods
    • Specification of attributes and implementation of methods comes last