Code Explanation:
๐น Line 1: Import cached_property
from functools import cached_property
Imports the cached_property decorator.
๐ It works like a property, but once the value is calculated, Python stores (caches) it and reuses the same value on future accesses.
๐น Line 2: Create Class
class A:
A class named A is created.
๐น Line 3–5: Define Cached Property
@cached_property
def x(self):
return []
This creates a property named:
x
Whenever a.x is accessed for the first time, Python executes:
return []
and stores that returned list inside the object.
๐น Line 7: Create Object
a = A()
An object of class A is created.
Current state:
a
⚠️ x() has not run yet.
Because cached_property is lazy.
๐น Line 9: Access a.x
a.x.append(1)
Before .append(1) runs, Python evaluates:
a.x
Since this is the first access:
Python executes:
return []
A new list is created:
[]
and cached.
๐น Internal State After First Access
Python now stores:
a.x → []
Think of it like:
{
"x": []
}
inside the object.
๐น Line 9 Continues: Execute Append
a.x.append(1)
becomes:
[].append(1)
List changes from:
[]
to:
[1]
Now cached value is:
a.x → [1]
๐น Line 11: Print a.x
print(a.x)
Python checks:
Has x already been cached?
✅ Yes
Therefore Python does NOT execute:
return []
again.
Instead it directly returns the cached list:
[1]
๐น Line 12: Print Output
print([1])
Output:
[1]

0 Comments:
Post a Comment