-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions_as_objects.py
More file actions
104 lines (68 loc) · 1.98 KB
/
functions_as_objects.py
File metadata and controls
104 lines (68 loc) · 1.98 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# Functions as objects — in Python, functions are first-class objects.
#
# This means a function can be:
# - Assigned to a variable
# - Stored in a list or dictionary
# - Used as an attribute of an object
# - Passed as an argument to another function
# - Returned as the result of a function call
def greet(name):
return f'Hello, {name}!'
# --- Assign a function to a variable ---
say_hello = greet
print(say_hello('Alice'))
# --- Function as an attribute of an object ---
class Greeter:
def __init__(self, func):
self.greet_func = func
my_greeter = Greeter(greet)
print(my_greeter.greet_func('Bob'))
# --- Functions in a list ---
def add1(x):
return x + 1
def subtract1(x):
return x - 1
func_list = [greet, add1, subtract1]
for func in func_list:
if func == greet:
print(func('Charlie'))
else:
print(func(10))
# --- Functions as dictionary keys ---
func_dict = {
greet: 'Greeter function',
add1: 'Add one function',
subtract1: 'Subtract one function',
}
for func, description in func_dict.items():
if func == greet:
print(f'{description}: {func("Dave")}')
else:
print(f'{description}: {func(10)}')
# --- Passing a function as an argument ---
def execute(func, value):
return func(value)
print(execute(greet, 'Eve'))
# --- Returning a function ---
def get_greeting_function():
return greet
greet_func = get_greeting_function()
print(greet_func('Frank'))
# --- Higher-order functions ---
# Functions that take or return other functions.
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def apply(f, x, y):
return f(x, y)
print(apply(add, 10, 1)) # 11
print(apply(subtract, 10, 1)) # 9
# --- Function composition ---
# compose(f, g) returns a new function that applies g then f.
def compose(f, g):
return lambda x: f(g(x))
add2 = compose(add1, add1)
print(add2(10)) # 12
do_nothing = compose(add1, subtract1)
print(do_nothing(10)) # 10