🎓 A1Learner
🔍
0 of 52 lessons completed

Python Designing a Small Class

A small class is a class that does one job well. It holds a few pieces of data and the methods that work on them.

One job, one class

Book holds a title and an author. It also holds a page count. Nothing else belongs here yet.

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

book = Book("Dune", "Frank Herbert", 412)
print(book.title)
print(book.pages)

A method for each action

read() adds pages to pages_read. Two calls show the total growing.

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
        self.pages_read = 0

    def read(self, pages):
        self.pages_read = self.pages_read + pages
        return self.pages_read

book = Book("Dune", "Frank Herbert", 412)
print(book.read(40))
print(book.read(30))

__str__ gives a clear print

__str__ returns the title and the author. print() shows that text for the book.

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

    def __str__(self):
        return self.title + " by " + self.author

print(Book("Dune", "Frank Herbert", 412))

Example

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages
        self.pages_read = 0

    def read(self, pages):
        self.pages_read = self.pages_read + pages

    def is_finished(self):
        return self.pages_read >= self.pages

    def __str__(self):
        return self.title + " by " + self.author

book = Book("Dune", "Frank Herbert", 412)
book.read(200)
print(book)
print("Read:", book.pages_read)
print("Finished:", book.is_finished())
book.read(212)
print("Read:", book.pages_read)
print("Finished:", book.is_finished())

Key points

  • Small class: one job, a few attributes, and the methods for that job
  • Use __init__ to set every attribute the object needs
  • Use one method for each action the object can do
  • Use __str__ to give the object a clear printed form
  • Keep data that belongs together in the same class
  • Leave out data the class never uses

In this example, Book tracks reading progress. It stores the title, the author, the page total, and the pages read so far. read() adds pages to pages_read. is_finished() checks whether pages_read has reached the page count. After 200 pages the book is not finished. After 212 more pages the total reaches 412, so the last check is True.

Note

A class with one job is easier to test than a class with many jobs.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What belongs in a small Book class?