Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Count Objects Using a Class Attribute

Practice using a class attribute to track how many instances of a class have been created.

Python practice15 minClasses & Objects FundamentalsIntermediateLast updated April 7, 2026

Problem statement

Create a class named Widget that keeps track of how many Widget instances have been created so far using a class attribute. Each time a new Widget is constructed, the class attribute should increase by 1 and the instance should receive a unique id (starting at 1) stored in an instance attribute id. Provide a class method get_total() that returns the current total number of Widgets that have been created. Notes: - Use a class attribute (not a global variable) for the counter. - Assign each instance an id equal to the value of the counter after it increments. - get_total should be a class method (or a method that returns the class attribute) so it reflects the class-level count.

Task

Implement a class that maintains a class-level counter incremented each time a new instance is constructed and exposes the current count and a per-instance id.

Examples

Create two widgets and read total

Input

Widget(), Widget(); Widget.get_total()

Output

2

After creating two Widget instances, the class attribute should be 2. Each Widget should have ids 1 and 2 respectively.

Input format

No stdin. The learner implements the Widget class. Tests will create instances and call Widget.get_total() or inspect instance ids.

Output format

The tests evaluate expressions that return integers or tuples/other values. The harness compares the stringified result to the expected output.

Constraints

Do not use global variables outside the class. Use a class attribute to store the counter. The id for the first created instance must be 1.

Samples

Sample 1

Input

Widget(); Widget.get_total()

Output

1

One Widget created, total is 1.