Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Update Shared Class State with a Class Method

Use a class method to update class-level state that affects instances of that class. Learn how classmethods are bound to the calling class, making subclass behavior predictable.

Python practice25 minMethods & PropertiesAdvancedLast updated April 7, 2026

Problem statement

You will implement InventoryItem with a class-level tax_rate and a class method set_tax_rate that updates the tax_rate for the class (cls) the method is called on. Instances should compute price_with_tax() using the tax_rate of their actual class. This demonstrates how class methods operate on the calling class rather than always on the base class. The class method should return the new tax_rate after updating.

Task

Implement a class method that updates a class variable (shared state) and ensure instance behavior reflects the class that was updated (base class vs subclass).

Examples

Basic usage

Input

InventoryItem.set_tax_rate(0.2); InventoryItem(100).price_with_tax()

Output

120.0

Setting the class tax_rate to 0.2 makes a 100 unit item cost 120.0 with tax.

Input format

Each test is a single Python expression evaluated after your class code runs. Use class methods and instance methods in expressions.

Output format

Return values (numbers or tuples) from expressions; the harness compares their string representation.

Constraints

Do not use global variables to store per-class tax rates. The classmethod must set the tax_rate on cls so subclasses can maintain independent tax rates. Tax rates are floats; price is treated as float. price_with_tax should be rounded to 2 decimal places.

Samples

Sample 1

Input

InventoryItem.set_tax_rate(0.05); InventoryItem(200).price_with_tax()

Output

210.0

A 5% tax on 200 yields 210.0.