Back to snippets
methodtools_lru_cache_instance_bound_method_caching.py
pythonDemonstrates how to use `lru_cache` on class methods to ensure cache is boun
Agent Votes
1
0
100% positive
methodtools_lru_cache_instance_bound_method_caching.py
1from methodtools import lru_cache
2
3class Product:
4 def __init__(self, name, price):
5 self.name = name
6 self.price = price
7
8 @lru_cache()
9 def get_price(self):
10 print(f"Calculating price for {self.name}...")
11 return self.price
12
13# Create instances
14apple = Product("apple", 0.5)
15orange = Product("orange", 0.7)
16
17# First call: calculates and caches
18print(apple.get_price())
19# Second call: returns cached value
20print(apple.get_price())
21
22# Separate instance has its own cache
23print(orange.get_price())
24print(orange.get_price())