-
Notifications
You must be signed in to change notification settings - Fork 1
/
Intro_to_Decorators.py
63 lines (44 loc) · 1.35 KB
/
Intro_to_Decorators.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
'''
Introduction to
Decorators
'''
print("------------------------------------------------\n")
'''
First Class Objects
In Python, functions are first class objects which means that functions in Python can be
used or passed as arguments.
Properties of first class functions:
1.A function is an instance of the Object type.
2.You can store the function in a variable.
3.You can pass the function as a parameter to another function.
4.You can return the function from a function.
'''
# Example 1: Treating the functions as objects.
def shout(text):
return text.upper()
print(shout('Hello'))
yell = shout
print(yell('Hello'))
print("\n------------------------------------------------\n")
def greet(name):
return f"Hello, {name}!"
def welcome(name):
return f"Welcome, {name}!"
def say_hello(func, name):
message = func(name)
print(message)
say_hello(greet, "Alice")
say_hello(welcome, "Bob")
print("\n------------------------------------------------\n")
# Passing the function as an argument
def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
# storing the function in a variable
greeting = func("""Hi, I am created by a function passed as an argument.""")
print (greeting)
greet(shout)
greet(whisper)
print("\n------------------------------------------------")