Decorators are very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. But before diving deep into decorators let us understand some concepts that will come in handy in learning the decorators.
Following are important facts about functions in Python that are useful to understand decorator functions.
- In Python, we can define a function inside another function.
- In Python, a function can be passed as parameter to another function (a function can also return another function).
def
messageWithWelcome(
str
):
def
addWelcome():
return
"Welcome to "
return
addWelcome()
+
str
def
site(site_name):
return
site_name
print
messageWithWelcome(site(
"Python"
))
Output:
"Welcome to python"
Function Decorator
A decorator is a function that takes a function as its only parameter and returns a function. This is helpful to “wrap” functionality with the same code over and over again. For example, above code can be re-written as following.We use @func_name to specify a decorator to be applied on another function.
def
decorate_message(fun):
def
addWelcome(site_name):
return
"Welcome to "
+
fun(site_name)
return
addWelcome
@decorate_message
def
site(site_name):
return
site_name;
print
site(
"python"
)
Output:
"Welcome to python"
The above two programs has same results but have 2 different approaches.
Decorators can also be useful to attach data (or add attribute) to functions.
def
attach_data(func):
func.data
=
3
return
func
@attach_data
def
add (x, y):
return
x
+
y
print
(add(
2
,
3
))
print
(add.data)
Output:
5
3
Comments
Post a Comment