File tree Expand file tree Collapse file tree 10 files changed +126
-0
lines changed
python-callable-instances Expand file tree Collapse file tree 10 files changed +126
-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+ data = []
3+
4+ def average (new_value ):
5+ data .append (new_value )
6+ return sum (data ) / len (data )
7+
8+ return average
9+
10+
11+ class CumulativeAverager :
12+ def __init__ (self ):
13+ self .data = []
14+
15+ def __call__ (self , new_value ):
16+ self .data .append (new_value )
17+ return sum (self .data ) / len (self .data )
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 not in self .cache :
7+ self .cache [number ] = number * self (number - 1 )
8+ 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 Logger :
2+ def __init__ (self , filename ):
3+ self .filename = filename
4+
5+ def __call__ (self , message ):
6+ with open (self .filename , mode = "a" , encoding = "utf-8" ) as log_file :
7+ log_file .write (message + "\n " )
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+ import time
2+
3+ # class ExecutionTimer:
4+ # def __init__(self, func):
5+ # self.func = func
6+
7+ # def __call__(self, *args, **kwargs):
8+ # start = time.perf_counter()
9+ # result = self.func(*args, **kwargs)
10+ # end = time.perf_counter()
11+ # print(f"{self.func.__name__}() took {(end - start) * 1000:.4f} ms")
12+ # return result
13+
14+
15+ class ExecutionTimer :
16+ def __init__ (self , repetitions = 1 ):
17+ self .repetitions = repetitions
18+
19+
20+ def __call__ (self , func ):
21+ def timer (* args , ** kwargs ):
22+ result = None
23+ total_time = 0
24+ print (f"Running { func .__name__ } () { self .repetitions } times" )
25+ for _ in range (self .repetitions ):
26+ start = time .time ()
27+ result = func (* args , ** kwargs )
28+ end = time .time ()
29+ total_time += end - start
30+ average_time = total_time / self .repetitions
31+ print (
32+ f"{ func .__name__ } () takes "
33+ f"{ average_time * 1000 :.4f} ms on average"
34+ )
35+ return result
36+
37+ return timer
You can’t perform that action at this time.
0 commit comments