-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosures.py
63 lines (38 loc) · 858 Bytes
/
closures.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from dataclasses import dataclass
def closure():
counter = 0
def inner():
nonlocal counter
counter += 1
return counter
return inner
def generator():
counter = 1
while True:
yield counter
counter += 1
@dataclass
class Adder:
counter: int = 0
def run(self):
self.counter += 1
return self.counter
def run_closure() -> None:
c = closure()
for _ in range(3):
print(c())
def run_generator() -> None:
g = generator()
for _ in range(3):
print(next(g))
def run_adder() -> None:
adder = Adder()
for _ in range(3):
print(adder.run())
if __name__ == "__main__":
print("Running closure")
run_closure()
print("\nRunning generator")
run_generator()
print("\nRunning adder class")
run_adder()