Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Update a Shared Class Attribute and Observe the Change Across Instances

Practice using a class attribute shared across all instances and implement methods to read and update it. Observe how changing the class attribute affects existing and new instances.

Python practice25 minClasses & Objects FundamentalsAdvancedLast updated April 7, 2026

Problem statement

In Python, class attributes are shared across all instances of a class. You'll implement a Product class with a class attribute discount_rate that represents a global discount applied to product prices. Implement: - discounted_price(self): an instance method that returns the price after applying the current class-wide discount_rate. - set_discount(cls, new_rate): a class method that updates the class attribute discount_rate. Validate that new_rate is a number between 0 and 1 inclusive; if invalid, raise a ValueError. Your implementation should show that updating the discount via the class method immediately affects discounted_price for both new instances created after the update and existing instances created before the update.

Task

Implement instance and class methods that use and update a shared class attribute, and demonstrate that updating the class attribute affects all instances (both existing and new).

Examples

Basic usage

Input

Product.set_discount(0.1); Product('Notebook', 100).discounted_price()

Output

90.0

Setting a 10% discount then creating a product with price 100 returns 90.0 after discount.

Input format

You will implement methods on the Product class. Tests will call those methods via expressions like Product('A', 100).discounted_price() or (Product.set_discount(0.2), Product('B', 200).discounted_price())[1].

Output format

Each test expression should evaluate to a value (number). The harness converts the returned value to str(...) for comparison.

Constraints

- discount_rate must be a float between 0.0 and 1.0 inclusive. - discounted_price should return price * (1 - discount_rate) as a float. - set_discount must be a @classmethod. - Do not print; return values from methods.

Samples

Sample 1

Input

Product.set_discount(0.25); Product('Lamp', 40).discounted_price()

Output

30.0

25% discount on 40 yields 30.0.