
Fill in
@classmethod & @staticmethod
Normal methods receive the object as self. Two decorators change that:
@classmethodreceives the class itself, calledcls. Its favourite job is an alternative constructor: another way to build an object, like from a line of text.@staticmethodreceives 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:
- Make
from_linea class method. - Build the object with the class it was called on.
- A valid line contains exactly one
:.
Fill in the three ___ blanks:
- Make
from_linea class method. - Build the object with the class it was called on.
- A valid line contains exactly one
:.
main.py Python sleeping
Press Run to try your code, then Check to test it.