Build an Instance Cache
Advanced · Write the code · from __init__ vs __new__: What Actually Happens When You Create an Object
From the lesson: __init__ vs __new__: What Actually Happens When You Create an Object
When you write obj = MyClass(), it feels like one simple step. But under the hood, Python actually does two things: it creates the object, and then it initializes it. These are handled by two different methods - __new__ and __init__.
Read the lessonCreate a class Symbol that caches instances by name. If you call Symbol('x') twice, you should get the exact same object back. Use __new__ with a class-level dictionary for caching.
Add a guard in __init__ to prevent re-initialization.
Test it: create a = Symbol('x'), b = Symbol('x'), and c = Symbol('y'). Print whether a is b and whether a is c.
class Symbol:
# Your code here
pass
a = Symbol('x')
b = Symbol('x')
c = Symbol('y')
print(a is b)
print(a is c)
More __init__ and __new__ exercises
- Predict the Creation OrderAdvanced
- Subclass an Immutable TypeAdvanced
- Build a SingletonAdvanced
- Fix the Immutable SubclassAdvanced
All Python exercises · 50 practice problems · Metaprogramming quiz