Skip to content

Commit 5289dbf

Browse files
authored
Merge pull request #387 from realpython/python-callable-instances
Sample code for the callable instances article
2 parents f9f8a98 + a34b6ef commit 5289dbf

File tree

10 files changed

+126
-0
lines changed

10 files changed

+126
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
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/).
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
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()
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
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]

python-callable-instances/gui.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
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()
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
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}")
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
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")

python-callable-instances/power.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class PowerFactory:
2+
def __init__(self, exponent):
3+
self.exponent = exponent
4+
5+
def __call__(self, base):
6+
return base**self.exponent
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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

0 commit comments

Comments
 (0)