Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement a Private Attribute in a ClassE02. Add Getter and Setter Methods for an AttributeE03. Convert Attribute Access to a PropertyE

Problem No 3

Convert Attribute Access to a Property

Easy

8 minute session

Summary

Learn to replace direct attribute access with a property that performs conversion and validation.

Problem statement

You are given a Temperature class that stores a temperature value in Celsius. Refactor the interface so external users can read and write the temperature in Fahrenheit using a property named 'fahrenheit', while the class keeps Celsius internally in a protected attribute. The fahrenheit property should: - Return the Fahrenheit equivalent rounded to 2 decimal places. - Allow setting a Fahrenheit value which updates the internal Celsius value (also rounded to 2 decimal places). - Raise a ValueError if the resulting Celsius would be below absolute zero (-273.15°C). Provide small helper functions so tests can exercise the class behavior.

Task

Create a Temperature class that stores Celsius internally but exposes a Fahrenheit attribute via a property with getter and setter, including validation against absolute zero.

Examples

Read Fahrenheit

Input

get_fahrenheit(0)

Output

32.0

Explanation

0°C is 32°F; the property should return 32.0

Input format

For tests, helper functions are provided. Call get_fahrenheit(celsius) or set_fahrenheit_and_get_celsius(initial_celsius, new_fahrenheit).

Output format

A Python value (float) is returned from the helper functions; tests compare its string representation.

Constraints

- Use a protected/internal attribute (convention: _celsius) to store the Celsius value. - Fahrenheit conversions must be rounded to 2 decimal places. - Celsius must never be set below -273.15; raise ValueError in that case.

Samples

Sample input 0

get_fahrenheit(100)

Sample output 0

212.0

Explanation 0

100°C equals 212°F.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:44 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.