← Python from Scratch Lesson 65 of 78 · 10 XP

Methods: regular, class and static

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

A regular method receives the object (self). But there are two more kinds:

@classmethod receives the class (cls). Most often it's used for alternative constructors — "create an object from other data":

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    @classmethod
    def from_fahrenheit(cls, f):
        return cls((f - 32) * 5 / 9)

t = Temperature.from_fahrenheit(212)
t.celsius        # 100.0

@staticmethod receives neither the object nor the class. It's an ordinary function that logically belongs to the class:

    @staticmethod
    def is_freezing(celsius):
        return celsius <= 0

Temperature.is_freezing(-5)    # True

How to choose:

  • you need the object's data → a regular method;
  • you need the class to create an object → @classmethod;
  • you need neither → @staticmethod.

Task. Finish the Temperature class: a class method from_fahrenheit(f) and a static method is_freezing(celsius) that returns True at a temperature of 0 °C or below.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.