Lazy class instantiation in Python
What is a lazy class instantiation?
Lazy instantiation or Initialization is the skill of delaying an object creation, the calculation of any data or some other process till the first time it is required. In short, it is lazy evaluation specifically referring to the instantiation of either objects or other resources.
How it is done? It is achieved by increasing an accessor method that keeps a check whether a member(private) has initialized so far or not. If the condition is true, it returns directly. If not then s new instance is created(initialized) and is kept into member variables(elements) and returns just before its first use to the caller.
It makes sure to create the object only when it is actually required.
Python code: Lazy class instantiation
So, lazy instantiation makes instantiation work slow and get access only when needed.
Example: Mood#Boring.
So Boring will cone only when we need(being’lazy’)
- We can also increase sleep time.
- You may return any value
def later(p): def covered(*args, **kwargs): if hasattr(covered, '_cached_val'): return covered._cached_val outcome = p(*args, **kwargs) covered._cached_val = outcome return outcome return covered #driver code @later def costly(): print ("Processing costly function:") import time time.sleep(2) return 177 print (costly()) print (costly()) print (costly())
Output
Processing costly function : 177 177 177 [Program finished]
We can also implement the code in another way.
- We create two class Smartphone and Smartphones.
- It tells about the address where the objects are located.
class Smartphone(object): def __init__(self, product: str) -> None: self.itemlist = product class Smartphones(object): def __init__(self) -> None: self.products = {} def get_smartphone(self, item: str) -> Smartphone: if item not in self.products: self.products[item] = Smartphone(item) return self.products[item] if __name__ == '__main__': phones = Smartphones() print(phones.get_smartphone('Samsung')) print(phones.get_smartphone('Xaomi'))
Output
<__main__.Smartphone object at 0x717770db38>
<__main__.Smartphone object at 0x717770db70>
[Program finished]
I hope the code was easy to understand and implement. Try the code and if you have doubt drop a comment. Your feedback will be appreciated.
Leave a Reply