-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy patheverything_is_object.py
81 lines (61 loc) · 1.75 KB
/
everything_is_object.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
"""
You can assign functions to variables, store them in data structures,
pass them as arguments to other functions,
and even return them as values from other functions.
"""
def yell(text):
return text.upper() + "!"
print(yell("Hello"))
# assign to a variable
"""
This line doesn’t call the function.
It takes the function object referenced by yell and creates a second name,
bark, that points to it.
"""
bark = yell
print(bark("woof"))
"""
You can delete the function’s original name (yell). Since
another name (bark) still points to the underlying function
"""
del yell
try:
print(yell("Hello"))
except Exception as err:
print("yell function is deleted")
print(bark("woof"))
# Python attaches a string identifier to every function at
# creation time for debugging purposes.
print(bark.__name__)
# Functions Can Be Stored in Data Structures
funcs = [bark, str.lower, str.capitalize]
for f in funcs:
print(f, f("Hey there !"))
# Functions can be passed to other functions.
def greet(func):
greeting = func("Hi, I am a Python program")
print(greeting)
greet(bark)
# Functions that can accept other functions as arguments are also called higher-order functions.
# map function
high_list = list(map(bark, ["Hello", "hey", "hi"]))
print(high_list)
# Functions Can Be Nested
def speak(text):
print(text)
# inner function
def whisper(text):
if text == "Hello":
print("Hi")
else:
print("Hello")
# inner function call
whisper(text)
speak("Hi")
# Functions Can Capture Local State
def make_adder(n):
def add(x):
return x + n
return add
plus_3 = make_adder(3)
print(plus_3(4)) # expected -> 3 + 3