← Schedule

HW 5: Classes & objects

CMSC 141: Introduction to Python

Due Sunday, July 26, 11:59pm

So far your data has been loose: a number here, a list there. A class lets you bundle data together with the operations that belong to it. In this homework you'll build a small model of a file system, the same kind of thing you've been navigating with cd and ls since Homework 0. You'll write a File class and a Directory class, then use them together.

Run git pull, then cd hw5. Your classes go in hw5.py.

Goals

What this homework builds

This homework builds S14 (classes and objects). You'll see it on Quiz 5.

What a class is

A class is a blueprint. __init__ is the special method that runs when you make a new object; it sets up the object's instance variables, the data each object carries. self refers to the particular object being worked on. Here is a tiny complete class:

class Dog:
    def __init__(self, name):
        self.name = name      # an instance variable
        self.tricks = 0

    def learn_trick(self):
        self.tricks = self.tricks + 1    # a method that changes the object

    def __str__(self):
        return self.name + " knows " + str(self.tricks) + " tricks"

You'd use it like this:

d = Dog("Rex")     # __init__ runs, name is "Rex", tricks is 0
d.learn_trick()    # tricks is now 1
print(d)           # __str__ runs: "Rex knows 1 tricks"

The __str__ method is optional but handy: Python calls it automatically when you print an object, so you control how the object looks.

Exercise 1: the File class

Write a class File with:

>>> f = File("report.txt", 1200)
>>> f.rename("final.txt")
>>> print(f)
final.txt (1200 bytes)

Exercise 2: the Directory class

Write a class Directory with:

>>> photos = Directory("photos")
>>> photos.add_file(File("a.jpg", 100))
>>> photos.add_file(File("b.jpg", 250))
>>> photos.count()
2
>>> photos.total_size()
350

Notice what's happening in total_size: a Directory holds File objects, and the method reaches into each one for its .size. One kind of object containing many of another is how most real programs are organized.

Requirements summary

In hw5.py, the File class supports __init__, rename, and __str__ as shown, and the Directory class supports __init__, add_file, count, and total_size. To test your work, run uv run pytest from the hw5 directory. That runs the provided test_hw5.py against your code.

Testing your work

From inside the hw5 directory, run

uv run pytest

or test a single function with

uv run pytest -xvk file

This runs the tests in test_hw5.py against your hw5.py. Passing them all is a good sign your File and Directory classes are correct.

Questionnaire

Fill out QUESTIONS-05.txt and submit it with your code. You won't be able to get an S on the homework without it.

Submission

Submit hw5.py on Gradescope under "Homework 5." Pushing your GitHub repo with a finished QUESTIONS-05.txt is sufficient to submit the questionnaire.