4/20/2020

Agenda:

  • Review: classes

  • Defining classes

  • Different types of methods

  • Using objects

Notes:

point.py

"""
Class Example: Point
Aline N
Spring 2020
"""
class Point:

    def __init__(self, x, y):
        """
        Constructor
        Parameters:
            x (float) - coordinate along x axis
            y (float) - coordinate along y axis
        Return (Point) - implicitly returns a new object with type Point
        """
        self.x = x
        self.y = y

    def scale(self, factor):
        """
        Scales this point by factor
        Parameters:
            factor (float) - scale factor
        Return: None
        Side effects: changes x,y values of this Point
        """
        self.x = factor * self.x
        self.y = factor * self.y

    def setX(self, x):
        """
        Mutator/Setter
        Parameters (numeric): x
        Return (None)
        Side effects: None
        """
        self.x = x

    def setY(self, y):
        """
        Mutator/Setter
        Parameters (numeric): y
        Return (None)
        Side effects: None
        """
        self.y = y

    def getX(self):
        """
        Accessor/Getter
        Parameters: None
        Return (float): the x coordinate
        Side effects: None
        """
        return self.x

    def getY(self):
        """
        Accessor/Getter
        Parameters: None
        Return (float): the y coordinate
        Side effects: None
        """
        return self.y

    def __str__(self):
        return "%f,%f"%(self.getX(), self.getY())

# Best practices:
#  - define the class in its own file
#  - under __name__=='__main__', put code to test the class
#  - use import to use the class in other programs
if __name__ == '__main__':

    p = Point(5, -3) # internal state: x = 5, y = -3
    print("The point is", p)
    p.scale(10) # internal state: x = 50, y = -30
    print("The point is", p)

    p.setX(-4) # internal state: x = -4, y = -30
    p.setY(-8) # internal state: x = -4, y = -8
    print("The point is", p)
    p.scale(10) #internal state: x = -40, y = -80
    print("The point is", p)

movie.py

"""
Class Example: Movie
Aline N
Spring 2020
"""
class Movie:

    def __init__(self, title, duration, year, director, actors):
        """
        Constructor
        Parameters:
            title (str)
            duration (int) - minutes
            year (int) - year movie was made
            director (str) - name of director
            actors (list of str) - actors
        Return (Movie): implicitly returns a new object with type Movie
        """
        self.title = title
        self.duration = duration
        self.year = year
        self.director = director
        self.actors = actors

    def getTitle(self):
        return self.title

    def getYear(self):
        return self.year

    def getDuration(self):
        return self.duration

    def getDirector(self):
        return self.director

    def getActors(self):
        return self.actors

    def printCredits(self):
        """
        Prints credits for this movie
        Parameters: None
        Return: None
        Side effects: Prints to console
        """
        print("Title:              %20s"% self.title)
        print("Duration (minutes): %20d"% self.duration)
        print("Year:               %20d"% self.year)
        print("Director:           %20s"% self.director)
        print("Actors:")
        for i in range(len(self.actors)):
            actor = self.actors[i]
            print("\t", actor)

    def __str__(self):
        return "%s (%d)"%(self.getTitle(), self.getYear())

def main():
    movie1 = Movie(
        "The Shining",
        2*60+26,
        1980,
        "Stanley Kubrick",
        ["Jack Nicholson", "Shelley Duvall"])

    movie1.printCredits()
    if movie1.getYear() < 2000:
        print("%s is old!"%(movie1.getTitle()))

    # Create a movie object for Casablanca and print the credits
    movie2 = Movie(
         "Casablanca",
         60+42,
         1942,
         "Michael Curtiz",
         ["Humphrey Bogart", "Ingrid Bergman"])
    movie2.printCredits()
    print("Test the __str__ function", movie2)

    # Create a list of movies and print the director of each one
    movies = [movie1, movie2]
    for i in range(len(movies)):
        m = movies[i]
        print("Director: ", m.getDirector())

main()

4/22/2020

Agenda:

  • Exercise: class terms worksheet

  • Exercise: student.py

  • Object Oriented Programming (OOP)

  • Implementing a vending machine

Notes:

Class terminology worksheet

Answers:

  • Marked-up example

  • Answers:

    • init

    • self.center, self.radius

    • getCenter, getRadius

    • setCenter, setRadius

    • self, self.center, self.radius, radius

    • Point.init

    • Circle.init

    • Circle.str

    • Circle.computeArea

    • Point

    • str

    • float

student.py

Try fixing the errors in student.py so it outputs the following

Sally June (3.60)
Sally June, Esq (3.70)

Answer:

class Student:

   def __init__(self, name, gpa):
       self.name = name
       self.gpa = gpa

   def getName(self):
       return self.name

   def getGpa(self):
       return self.gpa

   def setName(self, name):
       self.name = name

   def setGpa(self, inputGpa):
       self.gpa = inputGpa

   def __str__(self):
       return "%s (%.2f)"%(self.name, self.gpa)

def main():

    student = Student("Sally June", 3.6)
    print(student)

    # Increase GPA by 0.1
    gpa = student.getGpa()
    student.setGpa(gpa + 0.1)

    # Modify name
    name = student.getName()
    student.setName(name + ", Esq")

    print(student)

if __name__ == "__main__":
   main()

4/24/2020

Agenda:

  • Object/Classes Terms

  • Exercise: snack.py

  • Interfaces & Implementations

  • Exercise: vendingmachine.py

Notes:

snack.py

The example from class has been extended to include comments!

class Snack:
  """
  Class for storing information about different types of snacks
  """

  def __init__(self, name, quantity, cost, description):
      """
      Constructor method for class Snack. Initializes member variables for
      storing name, quantity, cost, and description
      """
      # Create instance variables for the data
      self.foodName = name
      self.quantity = quantity
      self.cost = cost
      self.description = description

  def getName(self):
      """Return name of snack (str)"""
      return self.foodName

  def getQuantity(self):
      """Return quantity of snack (int)"""
      return self.quantity

  def getCost(self):
      """Return cost of snack (int)"""
      return self.cost

  def getDescription(self):
      """Return description of snack (str)"""
      return self.description

  def setName(self, name):
      """Set name of snack to name (str)"""
      self.foodName = name

  def setQuantity(self, quantity):
      """Set quantity of snack (int)"""
      self.quantity = quantity

  def setCost(self, cost):
      """Set cost of snack (int)"""
      self.cost = cost

  def setDescription(self, desc):
      """Return description of snack (str)"""
      self.description = desc

  def __str__(self):
      """
      Returns a string representation for this class
      Params: none
      Usage:
         snack = Snack("test", 0, 0, "")
         print(snack)
      """
      return "%s %d left, $%d, %s" \
        %(self.foodName, self.quantity, self.cost, self.description)

if __name__ == '__main__':
   food = Snack("test", 4, 1, "The best thing ever!")
   print(food)
   print(food.getName())

vendingmachine.py

The following program is incomplete but shows how to initialize and load classes based on data from a file. I’ve removed the print statements we used for debugging.

from snack import Snack

class VendingMachine:

  def __init__(self):
      """
      Constructor. Initializes a list of available snacks (empty to start) and
      calls a function to load the default file of snack information
      """
      self.foods = []
      self.loadSnacks("snacks.txt")

  def loadSnacks(self, filename):
      """
      Loads snack information from a file. Clears the old snacks from the
      machine.  Param filename (string): the file to load Returns: none
      """
      ifile = open(filename, "r")
      for line in ifile:
          tokens = line.strip().split(",")
          name = tokens[0]
          quantity = int(tokens[1])
          cost = int(tokens[2])
          desc = tokens[3]
          snack = Snack(name, quantity, cost, desc)
          self.foods.append(snack)

  def listSnacks(self):
      """
      Pretty prints the snacks in the vending machine.
      Hint: Use the following string formatting to match the sample output
          "%d) %-20s %d left\t$%d\t%s"
      Params: none
      Returns: none
      """
      print()
      print("="*30, "Vending Machine", "="*30)
      for i in range(len(self.foods)):
          print(self.foods[i])
      print("="*75)

  def buy(self, snack, money):
      """
      Buy a snack from the vending machine.
        Prints "Cannot find food" if the name is not a valid snack
        Prints "None left!" if the named snack is unavailable
        Prints "You can't afford it" if the snack costs too much
        Prints "You bought a snack!" if successful and decrements the snack qty
      Param snack (Snack): the snack to buy
      Param money (int): the available amount of money
      Returns: True is successful; False otherwise
      """
      pass

  def findSnack(self, name):
      """
      Searches for a snack matching name in the list of snacks
      Param name (string): the snack name to search
      Returns: found snack (type Snack) if found; None otherwise
      """
      return None # not found!

  def getSnack(self, idx):
      """
      Returns the snack at marker idx in the list of snacks
      Param idx (int): the snack id
      Returns: snack (type Snack) if found; None otherwise
      """
      return None # not found!

  def getNumSnacks(self):
      """
      Returns the number of snacks in the vending machine
      Params: none
      Returns (int): the number of snacks
      """
      return len(self.foods)

if __name__ == '__main__':

   playerMoney = 10
   machine = VendingMachine()

   print("You have $%d dollars to spend at the snack vending machine"%playerMoney)
   print("What would you like to buy?")
   machine.listSnacks()