Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Add a Property Getter and Setter for Validation

Create a Person class with an age property that validates and normalizes assignments.

Python practice8 minMethods & PropertiesBeginnerLast updated April 7, 2026

Problem statement

Implement a Person class that stores an age as a private attribute and exposes it via an age property. The age setter should validate and normalize incoming values: - Convert numeric values to integers (e.g., 29.9 -> 29). - Clamp values below 0 to 0 and values above 150 to 150. - The getter should return the normalized integer age. Provide a constructor that accepts an initial age and stores it using the property so validation runs on construction.

Task

Learn to implement a Python property with a getter and setter that enforces validation rules (clamping and type normalization).

Examples

Basic usage

Input

p = Person(25) p.age

Output

25

Constructor stores the age via the property. Getter returns the integer age.

Input format

A Python expression creating or modifying a Person instance, evaluated and its return value compared to the expected output.

Output format

The string representation of the returned value is compared to the expected output.

Constraints

- Age values are numeric (int or float). - Ages are clamped to the inclusive range [0, 150]. - No external libraries. - Use Python's @property decorator for getter and setter.

Samples

Sample 1

Input

p = Person(29.9) p.age

Output

29

Float is converted to int (truncated) and returned.