File tree Expand file tree Collapse file tree 10 files changed +158
-0
lines changed
python-callable-instances Expand file tree Collapse file tree 10 files changed +158
-0
lines changed Original file line number Diff line number Diff line change 1+ # Python's .__ call__ () Method: Creating Callable Instances
2+
3+ This folder provides the code examples for the Real Python tutorial [ Python's .__ call__ () Method: Creating Callable Instances] ( https://realpython.com/python-callable-instances/ ) .
Original file line number Diff line number Diff line change 1+ class Counter :
2+ def __init__ (self ):
3+ self .count = 0
4+
5+ def increment (self ):
6+ self .count += 1
7+
8+ def __call__ (self ):
9+ self .increment ()
Original file line number Diff line number Diff line change 1+ def cumulative_average ():
2+ sample = []
3+
4+ def average (new_value ):
5+ sample .append (new_value )
6+ return sum (sample ) / len (sample )
7+
8+ return average
9+
10+
11+ class CumulativeAverager :
12+ def __init__ (self ):
13+ self .sample = []
14+
15+ def __call__ (self , new_value ):
16+ self .sample .append (new_value )
17+ return sum (self .sample ) / len (self .sample )
Original file line number Diff line number Diff line change 1+ class Factorial :
2+ def __init__ (self ):
3+ self .cache = {0 : 1 , 1 : 1 }
4+
5+ def __call__ (self , number ):
6+ if number in self .cache :
7+ return self .cache [number ]
8+ else :
9+ self .cache [number ] = number * self .__call__ (number - 1 )
10+ return self .cache [number ]
Original file line number Diff line number Diff line change 1+ class MainWindow :
2+ def show (self ):
3+ print ("Showing the app's main window..." )
4+
5+ def __call__ (self ):
6+ self .show ()
7+
8+
9+ window = MainWindow ()
10+ window .show () # Or just window()
Original file line number Diff line number Diff line change 1+ class Demo :
2+ def __init__ (self , attr ):
3+ print (f"Initialize an instance of { self .__class__ .__name__ } " )
4+ self .attr = attr
5+ print (f"{ self .attr = } " )
6+
7+ def __call__ (self , arg ):
8+ print (f"Call an instance of { self .__class__ .__name__ } with { arg } " )
Original file line number Diff line number Diff line change 1+ class PowerFactory :
2+ def __init__ (self , exponent ):
3+ self .exponent = exponent
4+
5+ def __call__ (self , base ):
6+ return base ** self .exponent
Original file line number Diff line number Diff line change 1+ import json
2+
3+ import yaml
4+
5+
6+ class JsonSerializer :
7+ def __call__ (self , data ):
8+ return json .dumps (data , indent = 4 )
9+
10+
11+ class YamlSerializer :
12+ def __call__ (self , data ):
13+ return yaml .dump (data )
14+
15+
16+ class DataSerializer :
17+ def __init__ (self , serializer_strategy ):
18+ self .serializer_strategy = serializer_strategy
19+
20+ def serialize (self , data ):
21+ return self .serializer_strategy (data )
Original file line number Diff line number Diff line change 1+ from typing import NamedTuple
2+
3+
4+ class Item (NamedTuple ):
5+ name : str
6+ price : float
7+ quantity : int = 1
8+
9+
10+ class ShoppingCart :
11+ def __init__ (self ):
12+ self ._cart = []
13+ self ._total = 0.0
14+
15+ def add_item (self , item ):
16+ self ._cart .append (item )
17+ self ._total += item .price * item .quantity
18+
19+ def remove_item (self , item ):
20+ for cart_item in self ._cart :
21+ if cart_item .name == item .name :
22+ self ._total -= cart_item .price * cart_item .quantity
23+ self ._cart .remove (cart_item )
24+ break
25+
26+ def content (self ):
27+ print ("Items in cart:" )
28+ for item in self ._cart :
29+ print (
30+ f"- { item .name } : { item .quantity } x ${ item .price :.2f} "
31+ f" = ${ item .quantity * item .price :.2f} "
32+ )
33+ print (f"\n Total: ${ self ._total :.2f} " )
34+
35+ def __call__ (self ):
36+ print ("Resetting the cart..." )
37+ self ._cart = []
38+ self ._total = 0.0
Original file line number Diff line number Diff line change 1+ import time
2+
3+ # class time_execution:
4+ # def __init__(self, func):
5+ # self.func = func
6+
7+ # def __call__(self, *args, **kwargs):
8+ # start = time.time()
9+ # result = self.func(*args, **kwargs)
10+ # end = time.time()
11+ # print(f"{self.func.__name__}() takes {(end - start) * 1000:.4f} ms")
12+ # return result
13+
14+
15+ class time_execution :
16+ def __init__ (self , repetitions = 1 ):
17+ self .repetitions = repetitions
18+
19+ def __call__ (self , func ):
20+ def _timer (* args , ** kwargs ):
21+ result = func (* args , ** kwargs )
22+ total_time = 0
23+ print (f"Running { func .__name__ } () { self .repetitions } times" )
24+ for _ in range (self .repetitions ):
25+ start = time .time ()
26+ func (* args , ** kwargs )
27+ end = time .time ()
28+ total_time += end - start
29+ average_time = total_time / self .repetitions
30+ print (
31+ f"{ func .__name__ } () takes "
32+ f"{ average_time * 1000 :.4f} ms on average"
33+ )
34+ return result
35+
36+ return _timer
You can’t perform that action at this time.
0 commit comments