Code Explanation:
1. Defining the class
class Cache:
This defines a class named Cache.
The class will dynamically create attributes when they are first accessed.
2. Defining __getattr__
def __getattr__(self, name):
__getattr__ is a special method.
It is called only when an attribute is NOT found in:
the instance dictionary, or
the class.
name is the attribute name being accessed.
3. Creating the attribute dynamically
self.__dict__[name] = len(name)
This line adds a new attribute to the instance.
The attribute name is name.
The value stored is len(name) (length of the attribute name).
This is called lazy initialization or caching.
4. Returning the value
return len(name)
The method returns the computed value.
So the first access gives back the same value that was stored.
5. Creating an instance
c = Cache()
An object c of class Cache is created.
Initially, c.__dict__ is empty.
6. First attribute access
print(c.abc, c.abc)
๐น First c.abc
Python looks for abc in c.__dict__ → not found.
Python looks in the class Cache → not found.
__getattr__(self, "abc") is called.
len("abc") → 3.
abc is stored in c.__dict__ as:
{"abc": 3}
The value 3 is returned.
๐น Second c.abc
Python finds abc directly in c.__dict__.
__getattr__ is not called.
The cached value 3 is returned instantly.
✅ Final Output
3 3

0 Comments:
Post a Comment