Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use a Property Setter to Enforce a Value Range

Learn to use Python's @property setter to ensure an attribute always stays within a specified range.

Python practice25 minMethods & PropertiesAdvancedLast updated April 7, 2026

Problem statement

Create a RangedValue class that stores a numeric value constrained between a minimum and maximum. The class should: - Accept three arguments on initialization: value, min_value, max_value. - Store the current value in a property named value. - Ensure the stored value is always between min_value and max_value inclusive. If the provided value is below min_value, store min_value. If above max_value, store max_value. - Enforce the same clamping behavior when the value property is assigned to after initialization. - Raise a ValueError during initialization if min_value > max_value. Use a @property getter and setter to implement the behavior. The stored attribute should be private (e.g., _value).

Task

Implement a class that uses a property setter to automatically clamp values to a provided min/max range on both initialization and assignment.

Examples

Initialize with in-range value

Input

RangedValue(50, 0, 100).value

Output

50

50 is within 0..100 so it is stored unchanged.

Input format

The tests will create instances of RangedValue and access or assign the .value property. Example expression: RangedValue(20, 0, 100).value

Output format

Return the numeric current value of the .value property. The test harness compares str(value).

Constraints

Do not use external libraries. Implement logic using Python's @property decorator and a private attribute. Initialization must raise ValueError if min_value > max_value. Both initialization and subsequent assignments must be clamped to the range.

Samples

Sample 1

Input

RangedValue(-10, 0, 100).value

Output

0

Initial value -10 is below the minimum 0, so it's clamped and stored as 0.