Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement Validation in a Property Setter

Learn to enforce constraints using a property setter that validates assignments and raises ValueError for invalid data.

Python practice13 minEncapsulation & Access PatternsIntermediateLast updated April 8, 2026

Problem statement

Create a User class with a validated age property. The constructor should accept name and age. The age property must be an integer between 0 and 130 inclusive. If an invalid value is assigned to age (wrong type or out of range), the setter should raise a ValueError. Implement the age property (getter and setter) using Python's @property decorator and ensure the value is stored privately.

Task

Implement a class property setter that validates input types and ranges, preventing invalid state.

Examples

Simple creation

Input

User('Alice', 30).age

Output

30

Constructing a User with a valid age returns that age from the age property.

Input format

A class User(name: str, age: int). Tests will create instances and access or set the age property in a single-expression form.

Output format

Accessing .age should return the numeric age (as int).

Constraints

age must be an integer (not bool) and satisfy 0 <= age <= 130. On invalid assignment, raise ValueError. Use a private attribute to store the age (e.g., self._age).

Samples

Sample 1

Input

User('Bob', 25).age

Output

25

25 is within the allowed range and is an integer.