Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement a Class Method to Clone an Object with Changes

Implement a class method that produces a new instance by copying an existing one and applying specified attribute changes.

Python practice16 minMethods & PropertiesIntermediateLast updated April 7, 2026

Problem statement

Cloning (making a new instance similar to an existing one) is a common pattern. In this exercise you will implement a class method clone_with that takes an existing instance and keyword overrides, and returns a new instance where the original attributes are copied and the provided overrides applied. Requirements: - Implement the Product class with attributes name and price (both public instance attributes set in __init__). - Implement a class method clone_with(cls, original, **overrides) that: - Creates and returns a new Product instance copied from original. - Applies only attributes that already exist on the original to the new instance; if an override contains an unknown attribute, raise AttributeError. - Provide a helper function make_product_and_clone(name, price, overrides) used by tests: it creates a Product, clones it with overrides, and returns a tuple (orig_name, orig_price, clone_name, clone_price). - Ensure that modifying the clone does not affect the original (tests verify this indirectly).

Task

Write a class method clone_with that returns a new object with the same attributes as the original but with allowed provided overrides.

Examples

Change the price when cloning

Input

make_product_and_clone('Apple', 1.2, {'price': 2.0})

Output

('Apple', 1.2, 'Apple', 2.0)

The clone has the same name but the price override was applied to the new instance.

Input format

Calls to make_product_and_clone(name: str, price: float, overrides: dict).

Output format

A tuple (orig_name, orig_price, clone_name, clone_price) showing original and clone values.

Constraints

- clone_with must be a @classmethod. - Only attributes existing on the original can be overridden; unknown keys must raise AttributeError. - No external libraries. - Products are shallow-copied; attributes are primitives for this exercise.

Samples

Sample 1

Input

make_product_and_clone('Pen', 0.5, {'name': 'Blue Pen'})

Output

('Pen', 0.5, 'Blue Pen', 0.5)

Name changed on the clone while price stayed the same.