Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Validate Multiple Related Attributes with Properties

Design a Color class that keeps RGB and hex representations in sync and validates updates via properties.

Python practice25 minEncapsulation & Access PatternsAdvancedLast updated April 8, 2026

Problem statement

Create a Color class that stores an RGB color internally using private attributes and exposes the following properties: - r, g, b: integers 0..255. Setting any of these validates the value and updates the internal state. - hex: a string of the form '#rrggbb' (lowercase) representing the color. The setter accepts 6-digit hex (with or without a leading '#') and 3-digit shorthand (e.g. '#f0a'), case-insensitive, and updates r/g/b accordingly. - grayscale: an integer 0..255 representing the luminance of the color (use a standard luminance formula: 0.299*R + 0.587*G + 0.114*B rounded to nearest int). Setting grayscale should set r, g and b all to that grayscale value. All attribute access must use properties; internal storage must use name-mangled private attributes (e.g., __r). Validation errors (out-of-range or malformed hex) should raise ValueError. The hex getter always returns a lowercase, 6-digit string with a leading '#'. Implement the class so that updating any representation (r/g/b/hex/grayscale) keeps all representations consistent and validated.

Task

Use encapsulation, name mangling, and property getters/setters to validate and maintain consistency across related attributes (r, g, b, hex, grayscale).

Examples

Red to hex

Input

Color(255, 0, 0).hex

Output

#ff0000

Constructing a Color from RGB and reading hex returns lowercase 6-digit form with leading '#'.

Input format

The evaluator will call expressions that construct or access Color instances, e.g., Color(255,0,0).hex or Color(hex='#00ff00').g.

Output format

Expressions should evaluate to simple values (strings or integers). The test harness compares str(value) to the expected output.

Constraints

Do not use any external libraries. Use name-mangled private attributes for internal storage. Validate inputs and raise ValueError for invalid values. Support hex strings with or without a leading '#', 3- or 6-digit formats, and case-insensitivity.

Samples

Sample 1

Input

Color(hex='#00ff00').g

Output

255

Parsing a hex string sets the G channel to 255.