Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Implement an Instance Method to Update StateE02. Create a Class Method Constructor from a DictionaryE03. Write a Static Method Utility for ValidationE

Problem No 2

Create a Class Method Constructor from a Dictionary

Easy

10 minute session

Summary

Build a classmethod constructor that creates instances from a dictionary and use a property to expose a derived value.

Problem statement

Implement the classmethod from_dict(cls, data) for the Person class. The method should accept a dictionary and return a new Person instance. The dictionary may contain: - 'name' (preferred) or 'full_name' as the person's name - 'age' as an integer or numeric string; if missing, default age to 0 Also implement an @property is_adult that returns True when age >= 18, otherwise False. The constructor __init__(self, name, age) is provided. Requirements: - from_dict must not raise errors for missing keys; use sensible defaults as described. - convert 'age' to int when possible (e.g., '17' -> 17).

Task

Implement Person.from_dict as a @classmethod to construct a Person from a dict, and provide a property is_adult.

Examples

Create from dict

Input

Person.from_dict({'name': 'Alice', 'age': 30}).is_adult

Output

True

Explanation

Age is 30, so is_adult returns True.

Input format

A call to Person.from_dict(dict) returning a Person instance; tests then inspect attributes or properties.

Output format

Values returned from expressions on the resulting Person (strings/numbers/booleans).

Constraints

- Do not raise exceptions for missing keys. - Age should be an integer (convert if provided as string). - Use @classmethod for from_dict and @property for is_adult.

Samples

Sample input 0

Person.from_dict({'name':'Bob','age':'17'}).is_adult

Sample output 0

False

Explanation 0

Age '17' is parsed to 17, which is not adult.

Code editor
Loading editor…

AI assistant

Ask me anything!

Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.

Chat history is temporary and will not be saved.

03:43 PM

Free preview includes 1 Teach Theory response and 1 AI hint on each of the first 3 lessons in this module.