Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 7 · Instance and Class Methods

Instance and Class Methods

On this pageInstance MethodsClass MethodsUse Both When Needed

An instance method receives the calling object as self. A class method receives the class as cls. Choose according to which data the operation needs.

UML underlines class-level members; ordinary operations belong to instances. Here the underlined operation is implemented with Python’s @classmethod, rather than @staticmethod.

Library+name+holdings+opening_hours+add_book(book)+list_books()+set_opening_hours(hours)

Instance Methods

class Library:
    def __init__(self, name):
        self.name = name
        self.books = []  # unique to each library

    def add_book(self, book):   # instance method
        """Add a book to this library."""
        self.books.append(book)

    def list_books(self):       # instance method
        """Display all books in this library."""
        print(f"{self.name} Library Collection:")
        for book in self.books:
            print(" -", book)

# Create two libraries
central = Library("Central")
neighborhood = Library("Neighborhood")

# Add books to each branch
central.add_book("Hamlet")
central.add_book("Macbeth")
neighborhood.add_book("Faust")

central.list_books()
neighborhood.list_books()
Listing 292 — Instance Methods

Output

Central Library Collection:
 - Hamlet
 - Macbeth
Neighborhood Library Collection:
 - Faust

add_book changes one branch’s list. list_books prints that branch’s heading and books.

Class Methods

A decorator is an @... line above a definition that changes how it is used. @classmethod binds the class to the first parameter.

The activity diagram shows the call and assignment in order; rounded boxes are actions, with a start circle and an end bullseye.

Call Library.set_opening_hours(hours)Supply Library as clsAssign hours to cls.opening_hours
class Library:
    opening_hours = "09:00–17:00"   # shared by all libraries

    def __init__(self, name):
        self.name = name
        self.books = []

    @classmethod
    def set_opening_hours(cls, hours):   # class method
        """Update opening hours for all libraries."""
        cls.opening_hours = hours
Listing 293 — Class Methods

This defines a class method; the definition itself prints nothing.

Continue with that Library definition:

central = Library("Central")
neighborhood = Library("Neighborhood")

print(central.opening_hours)
print(neighborhood.opening_hours)

Library.set_opening_hours("08:00–20:00")

print(central.opening_hours)
print(neighborhood.opening_hours)
Listing 294 — Class Methods

Output

09:00–17:00
09:00–17:00
08:00–20:00
08:00–20:00

The class method changes the default hours used by both unshadowed instances.

Use Both When Needed

class Library:
    opening_hours = "09:00–17:00"

    def __init__(self, name):
        self.name = name
        self.books = []

    def add_book(self, book):
        self.books.append(book)

    def list_books(self):
        print(f"{self.name} Library Collection:")
        for book in self.books:
            print(" -", book)

    @classmethod
    def set_opening_hours(cls, hours):
        cls.opening_hours = hours

# Example usage
central = Library("Central")
branch = Library("Neighborhood")

central.add_book("Hamlet")
branch.add_book("Faust")

central.list_books()
branch.list_books()

Library.set_opening_hours("08:00–20:00")
print("Central hours:", central.opening_hours)
print("Branch hours:", branch.opening_hours)
Listing 295 — Use Both When Needed

Output

Central Library Collection:
 - Hamlet
Neighborhood Library Collection:
 - Faust
Central hours: 08:00–20:00
Branch hours: 08:00–20:00

The instance methods manage separate collections; the class method changes their shared default. A class does not need both kinds of method unless its responsibilities require them.

Try it: add a book to Central and confirm that the branch’s list stays unchanged.

Apply these two kinds of method in the library challenge, combining separate collections with a shared total.