Advanced
Write your own cached_property
Write a class lazy that works as a decorator for a method, like functools.cached_property. The first read of the attribute calls the method, and the result is stored on the instance. Later reads must not call the method again.
It must be a non-data descriptor (define __get__, do not define __set__). Reading it on the class (Report.total) must return the lazy object itself. Store the value in the instance's __dict__ under the method's name.
What Check tests
- The first read returns the computed value
- Several reads call the method only once
- The value is stored in the instance
__dict__ - A falsy result (such as 0) is cached too
- Deleting the attribute makes it compute again
- Each instance has its own value
- Reading it on the class returns the descriptor
- It is a non-data descriptor
- The program prints
Computed: 1
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.