Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use a Property Setter to Restrict Invalid Values

Learn to enforce value constraints with a Python property setter, using a private attribute and clear error types/messages.

Python practice15 minEncapsulation & Access PatternsIntermediateLast updated April 8, 2026

Problem statement

Create a class SafeTemperature that stores a temperature in Celsius. The value should be stored in a private attribute and exposed via a property named celsius. Implement the celsius setter to enforce the following rules: - Only numeric types (int or float) are allowed. Non-numeric assignments should raise a TypeError with message: "celsius must be a number". - The temperature cannot be below absolute zero (-273.15). Assignments below this should raise a ValueError with message: "celsius must be >= -273.15". - For safety, also cap the allowed temperature at a high bound of 1000 degrees Celsius; assignments above this should raise a ValueError with message: "celsius must be <= 1000". Also provide a read-only property fahrenheit that converts the stored Celsius temperature to Fahrenheit (c * 9/5 + 32). You should keep the temperature value in a private attribute (e.g., _celsius) and use the property to control access. Use clear, specific exception types and messages so callers can distinguish type errors from range errors.

Task

Implement a class with an encapsulated attribute and a property setter that validates type and range, raising appropriate exceptions for invalid assignments.

Examples

Basic usage and conversion

Input

t = SafeTemperature(0) (t.celsius, t.fahrenheit)

Output

(0, 32.0)

Creating with 0°C stores 0 in celsius; fahrenheit returns 32.0.

Input format

A single expression evaluated after your class is available, e.g., SafeTemperature(25).fahrenheit

Output format

Returnable Python values. Tests compare the string representation of the returned value.

Constraints

- Use a private attribute to store the Celsius value. - The celsius setter must raise TypeError for non-numbers and ValueError for out-of-range values with the exact messages described. - Provide a read-only fahrenheit property calculated from the current celsius value.

Samples

Sample 1

Input

SafeTemperature(100).fahrenheit

Output

212.0

100°C equals 212.0°F.