Editor

Build a Temperature Converter

Advanced · Write the code · from Python @classmethod vs @staticmethod: When to Use Each

From the lesson: Python @classmethod vs @staticmethod: When to Use Each

Imagine a company with three kinds of employees. Regular employees work on their own tasks (they need to know about themselves). Managers can hire new employees for the whole department (they need to know about the department).

Read the lesson

Create a Temperature class that stores temperature in Celsius:

1. __init__(self, celsius) stores the value

2. @classmethod from_fahrenheit(cls, f) - creates from Fahrenheit: (f - 32) * 5 / 9

3. @staticmethod is_freezing(celsius) - returns True if celsius <= 0

4. to_fahrenheit(self) - returns the Fahrenheit value: self.celsius * 9 / 5 + 32

Create a temperature using Temperature.from_fahrenheit(32). Print:

  • The celsius value (should be 0.0)
  • The result of to_fahrenheit() (should be 32.0)
  • The result of Temperature.is_freezing(0.0) (should be True)
  • # Build your Temperature class here

    More Classmethod and Staticmethod exercises

    All Python exercises · 50 practice problems · Object-Oriented Programming quiz