Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Support len() with __len__

Make a Sentence class compatible with Python's len() by implementing __len__.

Python practice9 minMagic Methods & Operator OverloadingBeginnerLast updated April 11, 2026

Problem statement

Write a class Sentence that accepts a text string. Implement the __len__ magic method so that len(sentence) returns the number of words in the sentence. Words are defined as sequences of non-whitespace characters separated by any whitespace (spaces, tabs, newlines). The class should handle empty strings and strings with extra whitespace correctly.

Task

Implement __len__ for a Sentence class so len(instance) returns the number of words in the sentence.

Examples

Counting words

Input

len(Sentence("Hello world"))

Output

2

The sentence contains two words: 'Hello' and 'world'.

Input format

The tests call len(Sentence(text)) where text is a string literal.

Output format

An integer representing the number of words in the sentence.

Constraints

- Use Python's definition of whitespace splitting (str.split()). - Return 0 for empty or whitespace-only strings.

Samples

Sample 1

Input

len(Sentence(" leading and multiple spaces "))

Output

4

split() ignores extra whitespace and counts 4 words.