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

Lecture 10: Classes and Object-Oriented Programming

Theme: Student Life at UM — using everyday campus experiences to build intuition for classes and objects.

Goal: Learn to bundle data and behavior together using Python classes.

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 = "10_lecture_object_oriented_programming.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)}")

1. The Problem with Procedural Code

You already know how to store data in dictionaries and write functions that operate on that data. That works fine for small programs. But as programs grow, things get hard to manage — you have to remember which keys each dict has, which functions work with which dicts, and nothing prevents you from mixing them up.

Let's see this play out.

In [ ]:
# One student, one function — works fine!

def is_upperclassman(student):
    return student["credits"] >= 60

alice = {"name": "Alice", "cane_id": "C12345", "major": "Biology", "credits": 75}

print(f"{alice['name']} is upperclassman: {is_upperclassman(alice)}")
# Clean, simple, no issues.
In [ ]:
# Scale up: 3 students, 2 courses, 3 functions
# You have to mentally track which dict has which keys

alice = {"name": "Alice", "cane_id": "C12345", "major": "Biology", "credits": 75}
bob = {"name": "Bob", "cane_id": "C67890", "major": "CS", "credits": 30}
carol = {"name": "Carol", "cane_id": "C11111", "major": "English", "credits": 90}

csc115 = {"name": "Python for Everyone", "code": "CSC115", "credits": 3, "capacity": 40, "enrolled": 38}
bio101 = {"name": "Intro Biology", "code": "BIO101", "credits": 4, "capacity": 30, "enrolled": 30}

def is_upperclassman(student):
    return student["credits"] >= 60

def get_student_label(student):
    return f"{student['name']} ({student['cane_id']})"

def has_open_seats(course):
    return course["enrolled"] < course["capacity"]

print(get_student_label(alice))
print(f"CSC115 has open seats: {has_open_seats(csc115)}")
In [ ]:
# What happens when you pass the WRONG dict to a function?
# Python does not stop you — it just gives nonsense or crashes.

# This SHOULD be a student, but we accidentally pass a course dict:
print(get_student_label(csc115))
# Output: "Python for Everyone (CSC115)" — that's not a student!

# Even worse — csc115 HAS a "credits" key, so this silently returns nonsense:
print(f"Is CSC115 an upperclassman? {is_upperclassman(csc115)}")
# Python says False — meaningless! No error, no warning.

The problem is not that dicts are bad — they are great for storing data. The problem is that nothing in the code connects the data to the functions that operate on it. Any dict can be passed to any function, and Python will not warn you.

What if the data and the functions that operate on it were bundled together, so the code itself tells you what belongs with what?

That is what a class does.

When to use a class vs. a dict: If you just need to group some values together temporarily, a dict is fine. But when you find yourself writing multiple functions that all expect the same kind of dict, that is a sign you should use a class instead.


2. What is a Class?

A class is a template for creating objects. An instance is a specific object made from that template.

Think of it like forms at UM:

Template (Class) Specific Thing (Instance)
Blank Student ID form Your filled-out student ID
Course listing in the catalog CSC115 Section A, Spring 2026
Dorm room blueprint Room 412 in Hecht Tower
Meal plan contract Your personal meal plan

The university prints one blank form, then stamps out thousands of unique IDs from it. The form does not change; each student's card does.

         StudentID (class)          <-- the template
          /          \
         /            \
  alice (instance)   bob (instance)  <-- filled-out forms
  name = "Alice"     name = "Bob"
  major = "Biology"  major = "CS"
In [ ]:
# Simplest possible class — just a name and pass
class StudentID:
    pass

# Create two instances from the same template
student_a = StudentID()
student_b = StudentID()

# They are different objects, even though they came from the same class
print(f"student_a type: {type(student_a)}")
print(f"student_b type: {type(student_b)}")
print(f"Same object? {student_a is student_b}")
print(f"student_a id: {id(student_a)}")
print(f"student_b id: {id(student_b)}")

Python Convention: Naming Classes

Class names use CamelCase (also called PascalCase) — each word starts with a capital letter, no underscores:

Good (CamelCase) Bad
StudentID student_id, studentid
MealPlan meal_plan, Meal_Plan
Course course

Everything else — variables, functions, methods, attributes — uses snake_case:

  • is_upperclassman(), credits_earned, add_credits()

This convention is part of PEP 8, Python's official style guide.


3. __init__ and self

An empty class is not very useful. We need a way to store data on each instance when it is created.

  • __init__ is a special method that runs automatically when you create a new instance. Think of it as filling out the form.
  • self is how the instance refers to itself — "put MY name here, put MY major here."

An attribute is a piece of data stored on an instance, accessed with dot notation: student.name.

In [ ]:
# StudentID with __init__ — now each instance stores its own data
# Keep __init__ simple — just store the data that defines this object

class StudentID:
    def __init__(self, name, cane_id, major):
        self.name = name
        self.cane_id = cane_id
        self.major = major
In [ ]:
# Create two students from the same class
alice = StudentID("Alice", "C12345", "Biology")
bob = StudentID("Bob", "C67890", "Computer Science")

# Each instance has its own separate data
print(f"alice.name = {alice.name}")
print(f"alice.major = {alice.major}")
print(f"bob.name = {bob.name}")
print(f"bob.major = {bob.major}")

# Changing one does not affect the other
alice.major = "Biochemistry"
print("\nAfter change:")
print(f"alice.major = {alice.major}")
print(f"bob.major = {bob.major}")

Question 1: Create a StudentID (1 point)

Using the StudentID class defined above, create your own student ID.

  1. Create a StudentID instance with any name, Cane ID, and major you like. Store it in my_student_id.
  2. Access the name from your instance and store it in my_id_name.
In [ ]:
# YOUR CODE HERE
my_student_id = ...
my_id_name = ...

print(f"Student: {my_id_name}, {my_student_id.cane_id}, {my_student_id.major}")
In [ ]:
grader.check("q1_create_student_id")

Experiment (not graded)

Try these in a new cell below. Use fresh variable names so you do not overwrite your graded answers above.

  • Create a second StudentID with a different name and major. Print each attribute using dot notation.
  • What happens if you try to access an attribute that does not exist, like my_student_id.gpa?
  • Create two students and compare them with ==. Are they the same object?

4. Instance Methods

A method is a function that lives inside a class. Methods always take self as the first parameter so they can access and modify the instance's own data.

Methods are called on an instance using dot notation: alice.is_upperclassman().

Let's add some behavior to our StudentID class. We also need to track credits now, so we will add a credits_earned attribute. This is normal — you add attributes to a class as they become needed.

In [ ]:
class StudentID:
    def __init__(self, name, cane_id, major, credits_earned=0):
        self.name = name
        self.cane_id = cane_id
        self.major = major
        self.credits_earned = credits_earned  # default to 0 if not provided

    def is_upperclassman(self):
        """Return True if the student has earned at least 60 credits."""
        return self.credits_earned >= 60

    def add_credits(self, amount):
        """Add credits to this student's record."""
        self.credits_earned += amount
In [ ]:
# Create a student with 45 credits
alice = StudentID("Alice", "C12345", "Biology", credits_earned=45)
print(f"Credits: {alice.credits_earned}")
print(f"Upperclassman? {alice.is_upperclassman()}")

# Add credits — this changes Alice's data
alice.add_credits(20)
print("\nAfter adding 20 credits:")
print(f"Credits: {alice.credits_earned}")
print(f"Upperclassman? {alice.is_upperclassman()}")

# Bob is unaffected — each instance has its own data
bob = StudentID("Bob", "C67890", "CS")
print(f"\nBob's credits: {bob.credits_earned}")

Python Convention: Docstrings

Notice the triple-quoted strings right after each def line:

def is_upperclassman(self):
    """Return True if the student has earned at least 60 credits."""
    return self.credits_earned >= 60

These are called docstrings. They describe what the method does (not how). Python uses them for built-in help:

help(alice.is_upperclassman)

Good docstrings are short and start with a verb: "Return...", "Add...", "Check...".

Question 2: Call Instance Methods (1 point)

  1. Create a StudentID for a student named "Jordan" with Cane ID "C55555", major "Mathematics", and 50 credits earned. Store it in q2_student.
  2. Add 25 credits to Jordan's record using the appropriate method.
  3. Store Jordan's updated credit total in q2_credits_after.
  4. Check whether Jordan qualifies as an upperclassman (at least 60 credits) and store the result in q2_is_upper.
In [ ]:
# YOUR CODE HERE
q2_student = ...
...
q2_credits_after = ...
q2_is_upper = ...

print(f"Jordan's credits: {q2_credits_after}")
print(f"Upperclassman? {q2_is_upper}")
In [ ]:
grader.check("q2_instance_methods")

Experiment (not graded)

Try these in a new cell below. Use fresh variable names (not q2_student, q2_credits_after, etc.) so you do not affect your graded work.

  • Create a student with exactly 60 credits. Are they an upperclassman?
  • What about 59 credits?
  • What happens if you call add_credits(-10)? Should that be allowed?

5. The __str__ Method

When you print() a dictionary, Python shows you the contents. But when you print() a custom object, Python shows something ugly like <StudentID object at 0x7f...>. That is not helpful.

The __str__ method lets you control what print() shows.

In [ ]:
# Without __str__, printing an object is not useful
alice = StudentID("Alice", "C12345", "Biology", credits_earned=75)
print(alice)
In [ ]:
# Let's fix that by adding __str__ to our class

class StudentID:
    def __init__(self, name, cane_id, major, credits_earned=0):
        self.name = name
        self.cane_id = cane_id
        self.major = major
        self.credits_earned = credits_earned

    def is_upperclassman(self):
        """Return True if the student has earned at least 60 credits."""
        return self.credits_earned >= 60

    def add_credits(self, amount):
        """Add credits to this student's record."""
        self.credits_earned += amount

    def __str__(self):
        """Return a clean string representation of this student."""
        return f"StudentID({self.name}, {self.cane_id}, {self.major}, {self.credits_earned} credits)"
In [ ]:
# Now print shows our custom format
alice = StudentID("Alice", "C12345", "Biology", credits_earned=75)
print(alice)

# str() also uses __str__
alice_str = str(alice)
print(f"As string: {alice_str}")
print(f"Type: {type(alice_str)}")

Python Convention: Dunder Methods

__str__ and __init__ are dunder methods (short for "double underscore"). They have a special role in Python:

  • You define them, but Python calls them automatically.
  • You write print(alice), and Python calls alice.__str__() behind the scenes.
  • You write StudentID("Alice", ...), and Python calls __init__ behind the scenes.

Do not call dunder methods directly. Write print(alice), not alice.__str__(). Write str(alice), not alice.__str__(). Let Python do the calling.

There are many dunder methods (you have already used __init__). Another common one is __repr__, which is similar to __str__ but meant for developers and debugging. For now, __str__ is all you need.

Question 3: Add __str__ to MealPlan (1 point)

The MealPlan class below has __init__ already written. It stores a plan_name (like "Unlimited"), a meals_per_week count, and a price per semester.

  1. Complete the __str__ method so it returns a string in this exact format: "MealPlan: Unlimited (21 meals/week, $2500/semester)"
  2. Create a MealPlan with name "Unlimited", 21 meals per week, and price 2500. Store it in q3_meal_plan.
  3. Convert it to a string using str() and store the result in q3_meal_plan_str.
In [ ]:
class MealPlan:
    def __init__(self, plan_name, meals_per_week, price):
        self.plan_name = plan_name
        self.meals_per_week = meals_per_week
        self.price = price

    def __str__(self):
        ...

# YOUR CODE HERE
q3_meal_plan = ...
q3_meal_plan_str = ...

print(q3_meal_plan_str)
In [ ]:
grader.check("q3_meal_plan_str")

Experiment (not graded)

Try these in a new cell below. Use fresh variable names (not q3_meal_plan, etc.).

  • Create a MealPlan with plan name "Basic", 10 meals per week, and price 1500. Print it.
  • What does print() show if you remove the __str__ method entirely? (Hint: try defining a class without one.)
  • Can you make __str__ include extra info, like "Best value!" if the price is under 2000?

Day 1 buffer — time for questions or review.


Day 2: Building Real Things with Classes

Quick recap from Day 1:

  • Class: a template for creating objects (class StudentID:)
  • __init__: runs automatically when you create a new instance
  • self: how an instance refers to its own data
  • Attribute: data stored on an instance (self.name, self.credits_earned)
  • Method: a function inside a class that operates on self
  • __str__: controls what print() shows for your object

Today we will build a second class, make objects work together, and design a class of your own.

In [ ]:
# Re-establish classes for Day 2
# (Run this cell even if you completed Day 1 — it ensures everything is loaded)

class StudentID:
    def __init__(self, name, cane_id, major, credits_earned=0):
        self.name = name
        self.cane_id = cane_id
        self.major = major
        self.credits_earned = credits_earned

    def is_upperclassman(self):
        """Return True if the student has earned at least 60 credits."""
        return self.credits_earned >= 60

    def add_credits(self, amount):
        """Add credits to this student's record."""
        self.credits_earned += amount

    def __str__(self):
        """Return a clean string representation of this student."""
        return f"StudentID({self.name}, {self.cane_id}, {self.major}, {self.credits_earned} credits)"

print("StudentID class loaded for Day 2")

6. A Second Class: Course

Let's reinforce the pattern by building a second class from scratch. Every class follows the same structure: __init__ to store data, methods to add behavior, and __str__ to control printing.

Once you understand one class, you can build any of them.

In [ ]:
class Course:
    def __init__(self, name, course_code, credits, instructor, enrolled_count=0, capacity=40):
        self.name = name
        self.course_code = course_code
        self.credits = credits
        self.instructor = instructor
        self.enrolled_count = enrolled_count
        self.capacity = capacity

    def has_open_seats(self):
        """Return True if the course is not full."""
        return self.enrolled_count < self.capacity

    def __str__(self):
        """Return a formatted string like 'CSC115: Python for Everyone (3 credits)'."""
        return f"{self.course_code}: {self.name} ({self.credits} credits)"
In [ ]:
csc115 = Course("Python for Everyone", "CSC115", 3, "Prof. Kuhl", enrolled_count=38)
bio101 = Course("Intro Biology", "BIO101", 4, "Prof. Smith", enrolled_count=40, capacity=40)

print(csc115)
print(f"Has open seats? {csc115.has_open_seats()}")

print(bio101)
print(f"Has open seats? {bio101.has_open_seats()}")

Question 4: Build a Course Instance (1 point)

Using the Course class defined above:

  1. Create a Course for an art history class: name "Art History", course code "ARH101", 3 credits, instructor "Prof. Garcia", with 25 students enrolled and a capacity of 30. Store it in q4_course.
  2. Access the course code attribute and store it in q4_course_code.
  3. Check whether the course still has room for more students and store the boolean result in q4_has_seats.
In [ ]:
# YOUR CODE HERE
q4_course = ...
q4_course_code = ...
q4_has_seats = ...

print(q4_course)
print(f"Course code: {q4_course_code}")
print(f"Has open seats: {q4_has_seats}")
In [ ]:
grader.check("q4_build_course")

Experiment (not graded)

Try these in a new cell below. Use fresh variable names (not q4_course, etc.).

  • Create a course that is already full (enrolled equals capacity). What does has_open_seats() return?
  • What happens if enrolled is greater than capacity? Should the class prevent that?
  • Try printing your course. How does __str__ make this more readable than a dict?

7. Objects Working Together

The real power of classes is when objects interact. A student does not exist in isolation — they enroll in courses, and courses track how many students are enrolled.

This is called composition: one object contains references to other objects.

StudentID("Alice", ...)
  │
  ├── self.name = "Alice"
  ├── self.credits_earned = 0
  └── self.courses = [
        ├── Course("CSC115", 3 credits)
        └── Course("BIO101", 4 credits)
      ]

The student's courses list holds actual Course objects, not just strings. When Alice enrolls, both Alice and the course are updated.

In [ ]:
class StudentID:
    def __init__(self, name, cane_id, major, credits_earned=0):
        self.name = name
        self.cane_id = cane_id
        self.major = major
        self.credits_earned = credits_earned
        self.courses = []  # starts with no courses

    def is_upperclassman(self):
        """Return True if the student has earned at least 60 credits."""
        return self.credits_earned >= 60

    def add_credits(self, amount):
        """Add credits to this student's record."""
        self.credits_earned += amount

    def enroll(self, course):
        """Enroll this student in a course and update the course's enrollment count."""
        self.courses.append(course)
        course.enrolled_count += 1

    def total_credits(self):
        """Return the total credits across all enrolled courses."""
        total = 0
        for course in self.courses:
            total += course.credits
        return total

    def __str__(self):
        """Return a clean string representation of this student."""
        return (
            f"StudentID({self.name}, {self.cane_id}, {self.major}, "
            f"{self.credits_earned} credits, {len(self.courses)} courses)"
        )
In [ ]:
# Create a student and some courses
alice = StudentID("Alice", "C12345", "Biology")
csc115 = Course("Python for Everyone", "CSC115", 3, "Prof. Kuhl", enrolled_count=38)
bio101 = Course("Intro Biology", "BIO101", 4, "Prof. Smith", enrolled_count=28, capacity=30)

# Enroll Alice in both courses
alice.enroll(csc115)
alice.enroll(bio101)

# Check the results
print(alice)
print(f"Total credits this semester: {alice.total_credits()}")
print(f"Number of courses: {len(alice.courses)}")

# The course objects were updated too!
print(f"\nCSC115 enrolled: {csc115.enrolled_count}")  # 39 (was 38)
print(f"BIO101 enrolled: {bio101.enrolled_count}")    # 29 (was 28)

# Alice's course list holds actual Course objects, not just strings
print("\nAlice's courses:")
for course in alice.courses:
    print(f"  {course}")

Question 5: Enroll and Check Credits (1 point)

  1. Create a StudentID for "Sam" with Cane ID "C77777" and major "Music". Store it in q5_student.
  2. Create a Course for "Marine Biology" with code "BIO220", 4 credits, instructor "Prof. Diaz", 15 enrolled, capacity 25. Store it in q5_bio_course.
  3. Create a Course for "Digital Art" with code "ART150", 3 credits, instructor "Prof. Lee", 20 enrolled, capacity 25. Store it in q5_art_course.
  4. Enroll Sam in both courses.
  5. Store Sam's total credits from enrolled courses in q5_total_credits.
  6. Store the number of courses Sam is enrolled in as q5_num_courses.
In [ ]:
# YOUR CODE HERE
q5_student = ...
q5_bio_course = ...
q5_art_course = ...
...
...
q5_total_credits = ...
q5_num_courses = ...

print(f"Sam's total credits: {q5_total_credits}")
print(f"Number of courses: {q5_num_courses}")
print(f"BIO220 enrolled: {q5_bio_course.enrolled_count}")
In [ ]:
grader.check("q5_enroll_credits")

Experiment (not graded)

Try these in a new cell below. Use fresh variable names (not q5_student, etc.).

  • Create a student and enroll them in 3 courses. What does total_credits() return?
  • What happens if you enroll the same student in the same course twice? Is that a problem?
  • Try printing the student. How does the __str__ output change as you add courses?

Summary

Concept Syntax Student Life Example
Class class StudentID: The blank ID form template
__init__ def __init__(self, ...): Filling out the form when you arrive
Instance alice = StudentID(...) Alice's specific filled-out ID
Attribute self.name The name field on Alice's card
Method def is_upperclassman(self): Checking if a student has enough credits
__str__ def __str__(self): How the ID looks when you print it
Composition self.courses = [] The courses listed on your transcript

Key Takeaways

  1. A class bundles data and behavior together
  2. self is how an instance refers to its own data
  3. __init__ runs automatically when you create a new instance
  4. Methods are just functions that live inside a class and take self
  5. Objects can contain other objects — that is how you build real systems

Beyond the Notebook

In this lecture we defined classes inside Jupyter cells for convenience. In real projects, classes typically live in .py files. This week's lab will use that format — you will write classes in .py files and import them, which is the standard Python workflow.

In [ ]:
# You can inspect any class to see all its methods and attributes
# help() shows docstrings, dir() lists everything available

alice = StudentID("Alice", "C12345", "Biology", credits_earned=75)

print("=== dir(alice) — everything available on a StudentID ===")
# Filter out internal Python stuff to see just our methods and attributes
print([item for item in dir(alice) if not item.startswith("_")])

print("\n=== help(StudentID) — full documentation ===")
help(StudentID)

Conventions Recap

Here are the Python conventions we covered today:

Convention Example Why
CamelCase for class names StudentID, MealPlan Distinguishes classes from variables and functions
snake_case for everything else is_upperclassman, credits_earned Standard Python style (PEP 8)
Docstrings on methods """Return True if...""" Describe what a method does; used by help()
Dunder methods called by Python print(alice) not alice.__str__() Let Python's built-in functions trigger them
Keep __init__ simple Just store attributes Complex setup should go in separate methods
Default arguments in __init__ credits_earned=0 Let callers skip optional values
Class vs. dict Use a class when you have functions tied to data Classes prevent the "wrong dict" bugs we saw in Section 1

Build Your Own Class (not graded)

You have now seen the full pattern: __init__ to store data, methods to add behavior, __str__ to control printing, and composition to connect objects.

Challenge: Design and build your own class for something at UM. Here are some ideas:

Class Name Possible Attributes Possible Methods
DormRoom building, room_number, capacity, residents is_full(), add_resident(name)
ClubMembership club_name, member_name, role, dues_paid promote(new_role), pay_dues(amount)
ParkingPass pass_type, lot, vehicle, expiration is_expired(today), renew(months)
LibraryBook title, author, checked_out_by, due_date check_out(student), return_book()

Your class should have:

  • __init__ with at least 3 attributes
  • At least 1 method that does something useful
  • A __str__ method

There is no autograder for this. Use the empty cell below to write your class, create an instance, and test it. This is practice for the lab, where you will write classes in .py files.

In [ ]:
# Build your own class here!

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/10_lecture_object_oriented_programming/10_lecture_object_oriented_programming.ipynb
    • Windows: Open File Explorer -> Documents\CSC115\lecture_notebooks\10_lecture_object_oriented_programming\10_lecture_object_oriented_programming.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 10_lecture_object_oriented_programming.ipynb

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


You have completed the Lecture 10: Classes and Object-Oriented Programming notebook.


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

In [ ]:
grader.check_all()