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 2

Instantiate an Object

Easy

8 minute session

Summary

Practice creating objects and manipulating instance attributes after instantiation.

Problem statement

Define a class Counter with a method increment(self, amount=1). The Counter should store its current count in an instance attribute value. If value doesn't exist yet on the instance, assume it starts from 0. increment should add amount to value, store the new value on the instance, and return the new value.

Task

Create instances of a class and update their instance attributes. Implement a method that uses and updates instance state.

Examples

Basic increments

Input

c = Counter() c.increment() c.increment(5) c.value

Output

6

Explanation

Start at 0, increment by 1 (->1) then by 5 (->6). The value attribute holds the current count.

Input format

No input; learner must define the Counter class. Tests will call increment via expressions.

Output format

increment returns the new numeric value. The current count is stored as c.value.

Constraints

Do not assume value exists in __init__; handle missing attribute inside increment.

Samples

Sample input 0

c = Counter() c.increment(3) c.increment() c.value

Sample output 0

4

Explanation 0

Demonstrates multiple increments and that value persists on the instance.

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.