1+ #decorators-1.py
2+ # Decorators, as simple as it gets :)
3+
4+ # Decorators are functions that compliment other functions,
5+ # or in other words, modify a function or method.
6+
7+ # In the example below, we have a function named `decorated`.
8+ # This function just prints "This happened".
9+ # We have a decorator created named `inner_decorator()`.
10+ # This decorator function has an function within, which
11+ # does some operations (print stuff for simplicity) and then
12+ # returns the return-value of the internal function.
13+
14+ # How does it work?
15+ # a) The function `decorated()` gets called.
16+ # b) Since the decorator `@my_decorator` is defined above
17+ # `decorated()`, `my_decorator()` gets called.
18+ # c) my_decorator() takes a function name as args, and hence `decorated()`
19+ # gets passed as the arg.
20+ # d) `my_decorator()` does it's job, and when it reaches `myfunction()`
21+ # calls the actual function, ie.. decorated()
22+ # e) Once the function `decorated()` is done, it gets back to `my_decorator()`.
23+ # f) Hence, using a decorator can drastically change the behavior of the
24+ # function you're actually executing.
25+
26+
27+ def my_decorator (my_function ): # <-- (4)
28+ def inner_decorator (): # <-- (5)
29+ print ("This happened before!" ) # <-- (6)
30+ my_function () # <-- (7)
31+ print ("This happens after " ) # <-- (10)
32+ print ("This happened at the end!" ) # <-- (11)
33+
34+ return inner_decorator
35+ # return None
36+
37+
38+ @my_decorator # <-- (3)
39+ def decorated (): # <-- (2) <-- (8)
40+ print ("This happened!" ) # <-- (9)
41+
42+
43+ if __name__ == "__main__" :
44+ decorated () # <-- (1)
45+
46+
47+ '''
48+ O/P-
49+ This happened before!
50+ This happened!
51+ This happens after
52+ This happened at the end!
53+ '''
0 commit comments