Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Update Shared Class Data from an Instance Method

Learn how an instance method can update a class-level (shared) attribute and how to control that shared state across operations.

Python practice15 minClasses & Objects FundamentalsIntermediateLast updated April 7, 2026

Problem statement

You are to implement a simple counter class that keeps track of how many times any instance of the class has been incremented in total. The shared total must be a class attribute (shared among all instances). The instance method increment() should increase both the instance's own count and the shared class total. Additionally, implement a helper function make_and_increment(n_instances, increments_each) that: - Resets the shared class total to 0 (so each call reports only its own work), - Creates n_instances instances of the counter, - Calls increment() increments_each times on each instance, - Returns the class-level total after all increments. This exercise shows how instance methods can modify class-level data and how to ensure predictable, isolated results when running repeated scenarios.

Task

Implement an instance method that updates a class attribute and write a helper function that uses the class to perform repeated increments while isolating each run.

Examples

Single instance increments shared total

Input

c = SharedCounter(); c.increment(); SharedCounter.total

Output

1

Calling increment() on the instance increases both the instance count and the shared class attribute total.

Input format

A function call: make_and_increment(n_instances, increments_each)

Output format

An integer representing the total number of increments performed across all instances in this run.

Constraints

Do not use any external libraries. The shared total must be stored as a class attribute. increment() must be an instance method that updates the class attribute. make_and_increment must reset the shared class total to 0 at the start of each call.

Samples

Sample 1

Input

make_and_increment(2, 3)

Output

6

Two instances, each incremented 3 times -> total increments = 2 * 3 = 6.