These questions follow Objects and Classes and Objects Working Together. A class describes a kind of thing; an object is one actual thing; and the interesting work is deciding which class is responsible for which fact.

Reading

  1. Name each part of this line, and say what it produces: guide = Book("Exam Study Guide", "M. Okonjo", 1).
  2. Predict the output.
    class Locker:
        def __init__(self, number):
            self.number = number
            self.assigned_to = None
     
    a = Locker(101)
    b = Locker(101)
    print(a.number == b.number)
    print(a == b)
    a.assigned_to = "Nadia"
    print(b.assigned_to)
  3. Find the fault. t.is_available() fails. Why, and what is the one-word fix?
    class Tool:
        def __init__(self, name):
            self.name = name
            self.held_by = None
     
        def is_available():
            return self.held_by is None
  4. Find the fault. print(t.name) fails on this class. What went wrong, and what does Python say?
    class Tool:
        def __init__(self, name):
            name = name

Writing

  1. Write a Book class for the school library with title, author, and copies. Give it a lend() method that removes one copy and returns True, or returns False when none are left, and a __str__ that prints like Exam Study Guide by M. Okonjo (1 on the shelf).

  2. Using this catalogue, write titles_on_the_shelf(catalogue) and total_copies(catalogue):

    TitleAuthorCopies
    Exam Study GuideM. Okonjo1
    Short StoriesL. Tran4
    Data StructuresR. Whyte0
  3. Add a Member class with a name and a list of borrowed books, and a borrow(book) method that succeeds only if the book has a copy free. Show Rowan borrowing Short Stories and print both objects afterwards.

  4. Design, no code. A community centre wants a program for its Saturday drop-in program: people sign in, join one activity, and sign out. Write CRC cards for the classes you would create — name, responsibilities, collaborators. Then defend one noun you decided not to make a class.

Answers

Curriculum connection

A1.5

describe and use one-dimensional arrays of compound data types (e.g., objects, structures, records) in a computer program.

Link to original

A2.2

use modular design concepts that support reusable code (e.g., encapsulation, inheritance, method overloading, method overriding, polymorphism);

Link to original

A4.3

create fully documented program code according to industry standards (e.g., doc comments, docstrings, block comments, line comments);

Link to original

C1.1

decompose a problem into modules, classes, or abstract data types (e.g., stack, queue, dictionary) using an object-oriented design methodology (e.g., CRC [Class Responsibility Collaborator] or UML [Unified Modeling Language]);

Link to original

C1.4

apply the principle of reusability in program design (e.g., in modules, subprograms, classes, methods, and inheritance).

Link to original