Code Explanation:
๐น Step 1: Import cached_property
from functools import cached_property
cached_property is a modern Python feature.
It works like:
@property
but with one important difference:
The value is calculated only once
and then stored (cached).
๐น Step 2: Create Class
class A:
A new class named A is created.
๐น Step 3: Define Cached Property
@cached_property
def x(self):
return []
This creates a property named:
x
When accessed for the first time:
a.x
Python executes:
return []
and stores the result.
๐น Step 4: Create Object
a = A()
Object created:
a
At this moment:
x has NOT been executed yet
because cached properties are lazy.
๐น Step 5: Access a.x
a.x.append(1)
Before .append() can run, Python evaluates:
a.x
Since this is the first access:
Python executes:
def x(self):
return []
Result:
[]
This list is now cached internally.
Memory:
a.x ──► []
๐น Step 6: Execute Append
Now Python runs:
[].append(1)
List becomes:
[1]
Since the cached object itself was modified:
Memory becomes:
a.x ──► [1]
๐น Step 7: Print a.x
print(a.x)
Python checks:
Has x already been computed?
✅ Yes
So it does NOT execute:
return []
again.
Instead it returns the cached object:
[1]
๐น Step 8: Print Result
print([1])
Output:
[1]

0 Comments:
Post a Comment