-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26_advanced_functions.py
More file actions
56 lines (43 loc) · 1.09 KB
/
26_advanced_functions.py
File metadata and controls
56 lines (43 loc) · 1.09 KB
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
# 26 - Advanced Functions
# --- Functions Returning Functions ---
def make_multiplier(factor):
def multiplier(number):
return number * factor
return multiplier
multiply_by_3 = make_multiplier(3)
print(multiply_by_3(10)) # 30
# --- Functions as Arguments ---
def apply_operation(x, y, operation):
return operation(x, y)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
print(apply_operation(5, 3, add)) # 8
print(apply_operation(5, 3, subtract)) # 2
# --- Closures (Remembering State) ---
def counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
c = counter()
print(c()) # 1
print(c()) # 2
# --- Decorator (Manual Application) ---
def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper()
return wrapper
def greet():
return "hello"
greet_upper = uppercase_decorator(greet)
print(greet_upper()) # HELLO
# --- Decorator (Using @ Syntax) ---
@uppercase_decorator
def welcome():
return "welcome"
print(welcome()) # WELCOME