Skip to content

Commit 6adbf8b

Browse files
author
SanjayPradeeo
committed
step by step explanation of Decorators
More information and explained about decorators..
1 parent c018794 commit 6adbf8b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Decorators/WhatIsDecorators.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,52 @@ def is_returned():
6161
# None - basically is_called function returns is_returned method (which in turn prints "hello") so this throws None.
6262

6363

64+
# HERE'S SOMETHING IMPORTANT ..
6465

66+
# Functions and methods are called callable as they can be called.
67+
#
68+
# In fact, any object which implements the special method __call__() is termed callable. So, in the most basic sense, a decorator is a callable that returns a callable.
69+
#
70+
# Basically, a decorator takes in a function, adds some functionality and returns it.
71+
72+
73+
def make_pretty(func):
74+
def inner():
75+
print("I got decorated")
76+
func()
77+
return inner
78+
79+
def ordinary():
80+
print("I am ordinary")
81+
82+
83+
# Above we have two functions.. ordinary and make_pretty()
84+
85+
ordinary() #output : "I am ordinary"
86+
87+
# Now passing ordinary() as a parameter to make_pretty
88+
89+
sample = make_pretty(ordinary)
90+
sample()
91+
92+
# Here's the output..
93+
94+
# I got decorated
95+
# I am ordinary
96+
97+
# Generally, we decorate a function and reassign it as,
98+
#
99+
# ordinary = make_pretty(ordinary).
100+
# This is a common construct and for this reason, Python has a syntax to simplify this.
101+
#
102+
# We can use the @ symbol along with the name of the decorator function and place it above the definition of the function to be decorated. For example,
103+
#
104+
@make_pretty
105+
def ordinary():
106+
print("I am ordinary")
65107

108+
# is equivalent to
66109

110+
def ordinary():
111+
print("I am ordinary")
112+
ordinary = make_pretty(ordinary)

0 commit comments

Comments
 (0)