In [ ]:
# Initialize Otter
import otter
grader = otter.Notebook("11_lecture_object_oriented_part_deux.ipynb")

Lecture 11: Object-Oriented Programming Part 2 — Class Potpourri

Theme: Multiple domains, one process — learning to see classes everywhere.

Goal: Learn to identify classes in a problem description by thinking of nouns as classes and verbs as methods. There is no single "correct" class design — if your solution meets the contract, it is valid.

In [ ]:
# Validation: Check Python version and file location
import os
import sys

# Supported Python versions for this course
SUPPORTED_VERSIONS = ["3.12", "3.13"]
current_version = f"{sys.version_info.major}.{sys.version_info.minor}"

if current_version not in SUPPORTED_VERSIONS:
    raise EnvironmentError(
        f"Python version mismatch!\n"
        f"Supported: {', '.join(SUPPORTED_VERSIONS)}\n"
        f"Found: {current_version}\n"
        f"Please use Python 3.12 or 3.13 for this course."
    )
print(f"Python version: {current_version}")

# Expected filename for this assignment
EXPECTED_FILE = "11_lecture_object_oriented_part_deux.ipynb"

# Check file is in the correct directory
current_path = os.path.abspath("")
required_path_segment = os.path.join("Documents", "CSC115", "lecture_notebooks")
allowed_envs = ["submission", "dist", "live", "source"]
in_allowed_env = any(env in current_path for env in allowed_envs)

if required_path_segment not in current_path and not in_allowed_env:
    raise EnvironmentError(
        f"File location error!\n"
        f"This notebook should be in: ~/Documents/CSC115/lecture_notebooks/\n"
        f"Current location: {current_path}\n"
        f"Please move this file to the correct directory."
    )

# Verify filename (skip in grading/development environments)
if not in_allowed_env:
    if not os.path.exists(EXPECTED_FILE):
        notebooks = [f for f in os.listdir(".") if f.endswith(".ipynb")]
        raise EnvironmentError(
            f"Filename mismatch!\n"
            f"Expected: {EXPECTED_FILE}\n"
            f"Found notebooks: {notebooks}\n"
            f"Please rename your notebook to '{EXPECTED_FILE}'."
        )

print(f"File location: {os.path.join(current_path, EXPECTED_FILE)}")

Day 1: Nouns, Verbs, and Your First Classes

In Lecture 10, you learned how to write a class — __init__, self, methods, __str__. Now the question is: when should you make a class, and what should it look like?

The answer comes from a simple technique: read the problem description and look for nouns and verbs.


1. The Nouns and Verbs Technique

Here is a description of a coffee shop system:

"A coffee shop sells drinks. Each drink has a name, a size, and a price. Customers can place an order containing multiple drinks. The order tracks the customer's name and can calculate the total price."

Let's break this down. First, underline every noun:

"A coffee shop sells drinks. Each drink has a name, a size, and a price. Customers can place an order containing multiple drinks. The order tracks the customer's name and can calculate the total price."

Now underline every verb (actions):

"...can calculate the total price."

Here is the key insight:

Nouns become classes or attributes. Verbs become methods.

But which nouns are classes and which are just attributes? Ask yourself: does this noun have its own behavior (verbs)?

Word Noun or Verb? Has behavior? Maps to
Drink Noun Yes (could be customized, described) Class
Order Noun Yes (calculate total) Class
name, size, price Nouns No — just data Attributes on Drink
customer's name Noun No — just data Attribute on Order
calculate total price Verb — Method on Order

The rule of thumb: if a noun has verbs, it is probably a class. If it is just data, it is an attribute.

In [ ]:
# Here is what that analysis turns into as code:

class Drink:
    def __init__(self, name, size, price):
        self.name = name
        self.size = size
        self.price = price

    def __str__(self):
        return f"{self.size} {self.name} (${self.price:.2f})"


class Order:
    def __init__(self, customer_name):
        self.customer_name = customer_name
        self.drinks = []

    def add_drink(self, drink):
        self.drinks.append(drink)

    def calculate_total(self):
        total = 0
        for drink in self.drinks:
            total += drink.price
        return total

    def __str__(self):
        return f"Order for {self.customer_name}: {len(self.drinks)} drinks, ${self.calculate_total():.2f}"


# Try it out
latte = Drink("Latte", "Large", 5.50)
espresso = Drink("Espresso", "Small", 3.00)

my_order = Order("Alex")
my_order.add_drink(latte)
my_order.add_drink(espresso)

print(my_order)
print(f"Total: ${my_order.calculate_total():.2f}")

Notice how the code mirrors the English description. The nouns became classes and attributes. The verb "calculate total price" became the method calculate_total(). The Order contains Drinks — this is composition, which you saw in Lecture 10.

This technique works for any problem. Let's practice it.


2. Mini-Contract 1: Pet Adoption Center

Here is a scenario. Read it and identify the nouns and verbs yourself:

"An animal shelter tracks pets available for adoption. Each pet has a name, species, age, and whether it has been adopted yet. New pets start as not adopted. A pet can be adopted, and you should be able to get a friendly description of the pet."

Your job: build a class that satisfies the contract below. You can name your class whatever you want — Pet, ShelterAnimal, Adoptable, anything. Once you have built it, point the PetClass variable at it so the tests can find it.

Question 1: Pet Adoption Class (1 point)

Build a class for the pet adoption scenario above. Your class must satisfy this contract:

  1. Creating an instance with a name, species, and age results in a pet that is not yet adopted
  2. After calling an adopt method, the pet is marked as adopted
  3. str() on the pet returns a string containing the pet's name, species, and age (e.g., "Buddy (Dog, 3 years old)")

Point PetClass at your class when you are done.

In [ ]:
# YOUR CODE HERE — define your pet class below
...
    ...
    ...
    ...
PetClass = ...

# Try it out — this code shows how your class will be used.
# If it runs without errors, you are on the right track.
my_pet = PetClass("Buddy", "Dog", 3)
print(my_pet)
print(f"Adopted? {my_pet.is_adopted}")
my_pet.adopt()
print(f"Adopted after calling adopt? {my_pet.is_adopted}")
In [ ]:
grader.check("q1_pet_class")

3. Mini-Contract 2: Recipe + Cookbook

Now let's try a scenario with two classes that work together:

"A cookbook is a collection of recipes. Each recipe has a name, a list of ingredients, and a cook time in minutes. A cookbook has a title and holds multiple recipes. You should be able to add recipes to a cookbook, and find all recipes that can be made under a certain time limit."

Think about the nouns and verbs:

  • What are the nouns? Which ones have behavior?
  • What are the verbs? Which class should own each verb?
  • How do the two classes relate to each other?

Question 2: Recipe and Cookbook Classes (1 point)

Build two classes for the scenario above. Your classes must satisfy this contract:

  1. Creating a recipe with a name, list of ingredients, and cook time stores all three
  2. Creating a cookbook with a title starts with no recipes
  3. After adding 2 recipes to a cookbook, it holds both
  4. Filtering recipes by a time limit returns only recipes under that limit

Point RecipeClass and CookbookClass at your classes when you are done.

In [ ]:
# YOUR CODE HERE — define your Recipe and Cookbook classes below
...
    ...
    ...
...
    ...
    ...
    ...
RecipeClass = ...
CookbookClass = ...

# Try it out — this code shows how your classes will be used.
# If it runs without errors, you are on the right track.
pasta = RecipeClass("Pasta", ["noodles", "sauce", "cheese"], 20)
salad = RecipeClass("Salad", ["lettuce", "tomato", "dressing"], 5)

book = CookbookClass("Weeknight Dinners")
book.add_recipe(pasta)
book.add_recipe(salad)

print(f"Cookbook: {book.title}, {len(book.recipes)} recipes")
quick = book.quick_recipes(15)
print(f"Under 15 min: {[str(r) for r in quick]}")
In [ ]:
grader.check("q2_recipe_cookbook")

4. Mini-Contract 3: Gym Member + GymClass

This scenario has more interaction between the two classes:

"A gym tracks its members and the classes it offers. Each member has a name and a membership level (like 'basic' or 'premium'). Each gym class has a name, an instructor, a maximum capacity, and a roster of enrolled members. Members can sign up for a gym class if there is room. You should be able to check how many spots are left in a class and get a printable summary of the class."

Before you start coding, think about:

  • Which nouns become classes? Which are just attributes?
  • The sentence says "members can sign up for a gym class" — but which class should own the sign_up method? The Member? The GymClass? Either could work. Make a choice and go with it. We will discuss this after.

Question 3: Gym Member and GymClass (1 point)

Build two classes for the gym scenario above. Your classes must satisfy this contract:

  1. Creating a member with a name and membership level stores both
  2. Creating a gym class with a name, instructor, and capacity starts with an empty roster and the given capacity
  3. After signing up 2 members, the class shows 1 spot remaining (if capacity is 3)
  4. Signing up a member when the class is full does NOT add them
  5. str() on the gym class includes the class name and current enrollment count

Point MemberClass and GymClassClass at your classes when you are done.

In [ ]:
# YOUR CODE HERE — define your Member and GymClass classes below
...
    ...
    ...
...
    ...
    ...
    ...
    ...
MemberClass = ...
GymClassClass = ...

# Try it out — this code shows how your classes will be used.
# If it runs without errors, you are on the right track.
alice = MemberClass("Alice", "premium")
bob = MemberClass("Bob", "basic")
carol = MemberClass("Carol", "premium")

yoga = GymClassClass("Yoga", "Coach B", 2)
yoga.sign_up(alice)
yoga.sign_up(bob)
print(yoga)
print(f"Spots left: {yoga.spots_remaining()}")

yoga.sign_up(carol)
print(f"After trying to add Carol to a full class: {len(yoga.roster)} members")
In [ ]:
grader.check("q3_gym")

Day 1 ends here. Take note of which class you put the sign_up method on — we will discuss that choice next time.


Day 2: Who Does the Work?

Quick recap from Day 1:

  • Nouns in a problem description become classes (if they have behavior) or attributes (if they are just data)
  • Verbs become methods
  • You practiced this across three different domains: pets, recipes, and gym classes

Today we tackle the harder question: when two classes interact, which one should own the behavior?


5. Discussion: Who Does the Work?

In the gym exercise, the scenario said "members can sign up for a gym class." There are two natural ways to implement this:

Option A — The GymClass manages enrollment:

yoga.sign_up(alice)

The gym class knows its capacity and roster, so it makes sense for it to decide whether someone can join. The data needed to make the decision (capacity, current roster) lives on the GymClass.

Option B — The Member signs up for a class:

alice.sign_up(yoga)

The member is the one taking action in the real world, so it feels natural for the member to initiate enrollment. The verb "sign up" is something a member does.

Both are valid. There is no universal rule. The question is about responsibility — which object is best positioned to own this behavior?

Trade-offs to consider

Question to ask Option A (GymClass owns it) Option B (Member owns it)
Who has the data needed to decide? GymClass knows capacity and roster Member would need to access GymClass internals
Who is the "actor" in real life? The class accepts people The person signs up
What if requirements change? If members get a max-classes limit, Member needs involvement too If classes need waitlists, GymClass needs more control

The skill is not memorizing a rule. The skill is being able to reason about these trade-offs and make a judgment call. In practice, you will revisit these decisions as your program grows — and that is normal.

You will notice that the remaining exercises in this notebook test outcomes (did the state change correctly?) but do not prescribe which class owns the methods. That is your decision to make.

In [ ]:
# Both of these designs pass the same tests.
# The tests check outcomes, not which class has the method.

# --- Design A: GymClass owns sign_up ---
class GymClassA:
    def __init__(self, name, instructor, capacity):
        self.name = name
        self.instructor = instructor
        self.capacity = capacity
        self.roster = []

    def sign_up(self, member):
        if len(self.roster) < self.capacity:
            self.roster.append(member)

    def spots_remaining(self):
        return self.capacity - len(self.roster)


# --- Design B: Member owns sign_up ---
class MemberB:
    def __init__(self, name, level):
        self.name = name
        self.membership_level = level

    def sign_up(self, gym_class):
        if len(gym_class.roster) < gym_class.capacity:
            gym_class.roster.append(self)


class GymClassB:
    def __init__(self, name, instructor, capacity):
        self.name = name
        self.instructor = instructor
        self.capacity = capacity
        self.roster = []

    def spots_remaining(self):
        return self.capacity - len(self.roster)


# Both work! The tests do not care which design you chose.
print("Design A: GymClass owns sign_up")
print("Design B: Member owns sign_up")
print("Both are valid — the tests check what happened, not how you organized it.")

6. Full Contract 1: Library System

This exercise gives you a skeleton — the classes and their __init__ methods are already written. Your job is to add the checkout and return behavior. The key question: which class should own the checkout and return methods?

"A library lends books to patrons. Each book has a title, an author, and tracks whether it is currently checked out. Each patron has a name and a library card number, and can have multiple books checked out at once. Books can be checked out and returned. A patron should be able to list their currently borrowed books."

Here is the skeleton — do not modify __init__, just add methods:

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.is_checked_out = False

class Patron:
    def __init__(self, name, card_number):
        self.name = name
        self.card_number = card_number
        self.borrowed_books = []

You decide: does the Patron check out a book? Or does the Book get checked out by a patron? Or something else entirely? The tests only check outcomes.

Question 4: Library System (2 points)

Using the skeleton above as your starting point, build two classes with checkout and return behavior. Your classes must satisfy this contract:

  1. A new book starts as not checked out
  2. After checking out a book, it is marked as checked out
  3. After returning a book, it is no longer checked out
  4. A new patron starts with no borrowed books
  5. After a patron borrows 2 books, their borrowed list contains both
  6. After returning one book, only the other remains

Point BookClass and PatronClass at your classes when you are done.

In [ ]:
# YOUR CODE HERE — the skeleton is provided, add checkout and return behavior
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
        self.is_checked_out = False

    ...


class Patron:
    def __init__(self, name, card_number):
        self.name = name
        self.card_number = card_number
        self.borrowed_books = []

    ...
    ...


BookClass = ...
PatronClass = ...

# Try it out — this code shows how your classes will be used.
# If it runs without errors, you are on the right track.
book1 = BookClass("1984", "George Orwell")
book2 = BookClass("Dune", "Frank Herbert")
patron = PatronClass("Maria", "L12345")

patron.checkout(book1)
patron.checkout(book2)
print(f"Borrowed: {[b.title for b in patron.borrowed_books]}")

patron.return_book(book1)
print(f"After returning 1984: {[b.title for b in patron.borrowed_books]}")
print(book1)
In [ ]:
grader.check("q4_library")

7. Full Contract 2: Playlist Manager

This is the final exercise. No skeleton — you design everything from scratch.

"A music app manages playlists. Each song has a title, an artist, and a duration in seconds. A playlist has a name and contains songs. You can add and remove songs from a playlist. You should be able to get the total duration of a playlist and find all songs by a specific artist."

Apply the full process:

  1. Read the scenario and identify the nouns and verbs
  2. Decide which nouns are classes and which are attributes
  3. Decide which class owns each verb
  4. Build it and make sure it passes the contract

Question 5: Playlist Manager (2 points)

Build two classes for the music app scenario above. Your classes must satisfy this contract:

  1. A song stores a title, artist, and duration in seconds
  2. A new playlist starts with no songs
  3. After adding 3 songs, the playlist contains all 3
  4. Removing a song by title leaves the other 2
  5. Total duration returns the sum of all song durations in seconds
  6. Filtering by artist returns only that artist's songs

Point SongClass and PlaylistClass at your classes when you are done.

In [ ]:
# YOUR CODE HERE — define your Song and Playlist classes below
...
    ...
    ...
...
    ...
    ...
    ...
    ...
    ...
SongClass = ...
PlaylistClass = ...

# Try it out — this code shows how your classes will be used.
# If it runs without errors, you are on the right track.
s1 = SongClass("Bohemian Rhapsody", "Queen", 354)
s2 = SongClass("Another One Bites the Dust", "Queen", 215)
s3 = SongClass("Imagine", "John Lennon", 183)

playlist = PlaylistClass("Road Trip")
playlist.add_song(s1)
playlist.add_song(s2)
playlist.add_song(s3)

print(f"Playlist: {playlist.name}, {len(playlist.songs)} songs")
print(f"Total duration: {playlist.total_duration()} seconds")
print(f"Queen songs: {[str(s) for s in playlist.songs_by_artist('Queen')]}")

playlist.remove_song("Imagine")
print(f"After removing Imagine: {[s.title for s in playlist.songs]}")
In [ ]:
grader.check("q5_playlist")

Summary

Concept What We Learned
Nouns become Classes If a noun has behavior (verbs), it is probably a class
Nouns become Attributes If a noun is just data, it is an attribute on a class
Verbs become Methods Actions that operate on a class's data become methods
Composition Classes contain references to other classes
Ownership There is no single correct answer for which class owns a behavior — reason about trade-offs
Contracts Tests check what your class does, not what you named it

The Process

Every time you face a new problem:

  1. Read the description carefully
  2. Underline nouns — decide which are classes vs. attributes
  3. Underline verbs — decide which class owns each action
  4. Build the classes and test against the contract
  5. Revisit your design as requirements change — that is normal

Submitting to Gradescope

This file is saved on your computer — you do not need to download it from Jupyter.

  1. Find the file on your computer:

    • Mac: Open Finder -> Documents/CSC115/lecture_notebooks/11_lecture_object_oriented_part_deux/11_lecture_object_oriented_part_deux.ipynb
    • Windows: Open File Explorer -> Documents\CSC115\lecture_notebooks\11_lecture_object_oriented_part_deux\11_lecture_object_oriented_part_deux.ipynb
  2. Upload to Gradescope:

    • Go to gradescope.com and open this assignment
    • Click "Submit" and upload the .ipynb file
    • The filename must be exactly 11_lecture_object_oriented_part_deux.ipynb

Do NOT use File > Download in Jupyter — this can rename the file and cause submission errors.


You have completed the Lecture 11: Object-Oriented Programming Part 2 — Class Potpourri notebook.


To double-check your work, the cell below will rerun all of the autograder tests.

In [ ]:
grader.check_all()