Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count Objects Created by a Class

Implement a class that tracks how many instances of each class have been created and how many are currently alive.

Python practice24 minClasses & Objects FundamentalsAdvancedLast updated April 7, 2026

Problem statement

Create a base class InstanceCounter that automatically keeps two counters for each concrete class that inherits from it: - total_created(): the total number of instances that have ever been created for that specific class - current_alive(): the number of instances of that specific class that are currently alive (not yet garbage collected) Requirements and subtleties: - Counters must be maintained per class (each subclass gets its own counters, independent from the base class and other subclasses). - Counting must occur even if a subclass overrides __init__ and does not call super().__init__ (hint: use __new__). - Use a finalizer (weakref.finalize) or similar mechanism so that current_alive decreases when an object is garbage-collected (don't rely solely on __del__). - Provide class methods total_created() and current_alive() that return integers. - Implementation must work without requiring subclasses to remember to call super().__init__. You should provide an implementation of InstanceCounter. Tests will create dynamic subclasses of InstanceCounter to verify per-class isolation and garbage-collection behavior.

Task

Learn to use class attributes, __new__, and finalizers (weakref.finalize) to maintain per-class instance counters that are robust even when subclasses override __init__.

Examples

Basic usage

Input

C = type('C',(InstanceCounter,),{}); a = C(); b = C(); (C.total_created(), C.current_alive())

Output

(2, 2)

Two instances of class C were created; both are currently alive.

Input format

There is no external input. Your code defines the class InstanceCounter. Tests will instantiate dynamic subclasses and call the class methods.

Output format

The methods total_created() and current_alive() should return integers.

Constraints

Use only the Python standard library. Implementation must not require subclasses to call super().__init__ to be counted. Use per-class storage for counters.

Samples

Sample 1

Input

A = type('A',(InstanceCounter,),{}); [A() for _ in range(3)]; A.total_created()

Output

3

Three instances of subclass A were created; total_created returns 3.