Menu

Sign in to track your progress and unlock all features.

Theme style

Log in
01. Create a Simple ClassE02. Instantiate an ObjectE03. Implement a ConstructorE

Problem No 1

Create a Simple Class

Easy

6 minute session

Summary

Learn how to define a basic class and add a class attribute and an instance method.

Problem statement

Create a class named Book. The class should have a class attribute category set to the string 'literature'. Implement an instance method info(self) that returns a string formatted as '<title> by <author>' using the instance attributes title and author. If either attribute is missing on the instance, use 'Unknown' for that part instead of raising an error.

Task

Define a class with a class attribute and an instance method that uses instance attributes safely.

Examples

Basic usage

Input

b = Book() setattr(b, 'title', '1984') setattr(b, 'author', 'George Orwell') b.info()

Output

1984 by George Orwell

Explanation

We create a Book instance, attach title and author attributes, then call info() to get the formatted string.

Input format

No input; the learner must define the Book class. Tests will create instances and call methods via expressions.

Output format

The info() method should return a string like 'Title by Author'. Class attribute Book.category should be 'literature'.

Constraints

Do not assume instances always have title/author attributes; use getattr with defaults to avoid AttributeError.

Samples

Sample input 0

b = Book() setattr(b, 'title', 'Dune') setattr(b, 'author', 'Frank Herbert') b.info()

Sample output 0

Dune by Frank Herbert

Explanation 0

Demonstrates setting attributes after instantiation and calling info().

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.