Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Use a Class Method to Track Instance Count

Learn how to use a class method and a class variable to keep track of how many instances of a class have been created.

Python practice15 minMethods & PropertiesIntermediateLast updated April 7, 2026

Problem statement

You will implement a simple InstanceCounter class that keeps track of how many instances have been created. Use a class variable to store the count and a class method to read (and optionally reset) it. Also provide a helper function used by tests which creates N instances and returns the recorded count. Requirements: - Each time an InstanceCounter is instantiated, the shared counter should increase by 1. - Implement a class method get_count() that returns the current count. - Implement a class method reset_count() that sets the count back to zero (useful for tests). - Provide a helper function make_instances_and_get_count(n) that resets the counter, creates n instances, and returns the recorded count. This exercise focuses on when and how to use class variables and class methods rather than instance attributes.

Task

Implement an __init__ that updates a class-level counter and a classmethod to read and reset that counter.

Examples

Create 3 instances and read the count

Input

make_instances_and_get_count(3)

Output

3

reset_count is called by the helper, then three instances are created; get_count returns 3.

Input format

A single integer n passed to the helper function make_instances_and_get_count(n).

Output format

An integer representing how many InstanceCounter objects were created.

Constraints

- Use a class variable (not a global or instance attribute) to store the count. - get_count and reset_count must be class methods (use @classmethod). - make_instances_and_get_count must return the integer count. - No external libraries.

Samples

Sample 1

Input

make_instances_and_get_count(0)

Output

0

Creating zero instances should leave the counter at zero.