Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Enforce Type Checking in a Property Setter

Implement a property setter that enforces type and value constraints using Python's property and a private (name-mangled) attribute. Learn to raise appropriate exceptions for invalid assignments.

Python practice15 minEncapsulation & Access PatternsIntermediateLast updated April 8, 2026

Problem statement

Create a Circle class with a radius property. The radius setter must enforce two rules: 1. Type check: only allow int or float. If assigned a value of any other type, raise a TypeError. 2. Value check: only allow non-negative numbers (>= 0). If assigned a negative number, raise a ValueError. Store the radius in a private attribute using name mangling (e.g., __radius) to demonstrate encapsulation. Provide small helper functions to facilitate automated tests: try_set_radius(value) should attempt to set a Circle's radius and return 'OK' if successful or the exception class name (e.g., 'TypeError') if an exception was raised; get_radius_after_set(value) should attempt to set and then return the current radius. Do not call the property's setter inside __init__ in a way that will break starter code; assign the private attribute directly in __init__ to avoid invoking an unimplemented setter while the learner works on it.

Task

Write a class with a property whose setter enforces that assigned values are numeric (int/float) and non-negative. Use name-mangled private storage and raise TypeError or ValueError on bad inputs.

Examples

Valid numeric assignment

Input

c = Circle(1) c.radius = 2.5 c.radius

Output

2.5

Assigning a float 2.5 is allowed, so the getter returns 2.5.

Input format

The harness evaluates expressions (after the learner's code). Use the provided helper functions try_set_radius(value) and get_radius_after_set(value) or instantiate Circle and access its .radius property.

Output format

Return the final value (e.g., numeric radius) or helper function results. Tests compare the string form of the returned value to the expected string.

Constraints

Implement the radius setter to: - Raise TypeError if value is not int or float. - Raise ValueError if value is negative. - Use a name-mangled private attribute (e.g., __radius) for storage. - Do not use external libraries.

Samples

Sample 1

Input

get_radius_after_set(0.0)

Output

0.0

Zero is a valid non-negative number; setter accepts it and getter returns 0.0.