Fill in

@classmethod & @staticmethod

Normal methods receive the object as self. Two decorators change that:

  • @classmethod receives the class itself, called cls. Its favourite job is an alternative constructor: another way to build an object, like from a line of text.
  • @staticmethod receives neither. It's a plain helper function that lives inside the class because it belongs with it.
class Island:
    def __init__(self, name, size):
        self.name = name
        self.size = size

    @classmethod
    def from_text(cls, text):        # "Mossreach/12"
        name, size = text.split("/")
        return cls(name, int(size))  # same as Island(...)

    @staticmethod
    def is_big(size):
        return size > 10

isle = Island.from_text("Mossreach/12")
print(Island.is_big(isle.size))      # True

Why cls(...) instead of Island(...)? If a subclass like VolcanicIsland calls from_text, cls is VolcanicIsland, so you get the right kind of object for free.

Assignment

Fill in the three ___ blanks:

  1. Make from_line a class method.
  2. Build the object with the class it was called on.
  3. A valid line contains exactly one :.