-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorator.py
More file actions
41 lines (27 loc) · 1015 Bytes
/
decorator.py
File metadata and controls
41 lines (27 loc) · 1015 Bytes
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
# Decorators in Python
# A decorator is a function that takes another function as an argument,
# extends its behavior, and returns a new function.
# Decorators are often used to add functionality to existing functions
# without modifying their code.
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print("Wrapper executed this before {}".format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display():
print("Display function executed.")
display()
# example 2:
def login_required(func):
def wrapper(*args, **kwargs):
if args[0] == "admin":
return func(*args, **kwargs)
else:
return "Access Denied"
return wrapper
@login_required
def view_dashboard(user):
return "Welcome to the dashboard!"
print(view_dashboard("admin")) # Output: Welcome to the dashboard!
print(view_dashboard("guest")) # Output: Access Denied