Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Parse Input with a Static Method Helper

Learn to use a @staticmethod as a helper to parse input strings into structured data for a class.

Python practice15 minMethods & PropertiesIntermediateLast updated April 7, 2026

Problem statement

Create a Rectangle class that accepts a single string describing its size and initializes width and height using a static helper method. The static method parse_size must accept size strings in any of these formats: "WIDTHxHEIGHT", "WIDTH X HEIGHT", "WIDTH,HEIGHT", or "WIDTH:HEIGHT" (spaces around numbers are allowed). Both width and height should be parsed as non-negative integers. If parsing fails or values are negative, raise a ValueError. The Rectangle class should also expose an instance method area() that returns the product of width and height.

Task

Implement a static method to parse different size string formats and use it in __init__ to initialize instance attributes. Provide an instance method to compute area.

Examples

Basic usage

Input

Rectangle('3x4').area()

Output

12

parse_size splits '3x4' into width=3 and height=4; area returns 3*4 = 12.

Input format

A single string describing the rectangle size (e.g. '10x5', ' 6 , 7 ').

Output format

area() returns an integer (width * height).

Constraints

- Supported separators: 'x' or 'X', ',', ':' - Whitespace around numbers should be ignored - Width and height must be integers >= 0 - If parsing or validation fails, raise ValueError

Samples

Sample 1

Input

Rectangle(' 6 , 7 ').area()

Output

42

Whitespace is ignored, parsed as width=6 height=7, area 42.