python - what is decorators
Python decorators
USING FUNCTION AS DECORATORIn simple words, it decorates (beautify) a callable objects (function, methods or class)! In a technical word, it takes a callable object (say function ) and extends (decorate) behavior of called object.
Let us create a decorator function - new_decorator
decorator function
1- take another function as arguments - func_argument
2- have a wrapper function - wrap_func
2- return wrapper function - wrap_func
Decorator function is preceded with @ sign when called ( i is called pie syntax). It follow with the function need to be called - my_function
1 def new_decorator(func_argument):
2
3 def wrap_func():
4 print 'Code here before executing function'
5
6 # then execute function that has been passed
7 func_argument()
8
9 print 'Code here will execute after function'
10
11 return wrap_func()
12
13 @new_decorator
14 def my_function():
15 print 'Hello, Ansari'
A decorator is equivalent to
my_function = new_decorator(my_function)
Output
Code here before executing function
Hello, Ansari
Code here will execute after function
Reference
- code url
- https://realpython.com/blog/python/primer-on-python-decorators/
Another Decorator Example
def change_uppercase(f):
"""take a function f as argument and return function upper_case"""
def upper_case(*args, **kwargs):
x = f(*args, **kwargs)
return x.upper()
return upper_case
@change_uppercase
def print_string(s):
return s
print_string("CaMelCaSe - this is Camel Case")
Out[49]: 'CAMELCASE - THIS IS CAMEL CASE'
code_url
USING CLASS AS DECORATOR
Code
class CallCount:
def __init__(self, f):
self.f = f
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.f(*args, *kwargs)
def get_count(self):
return self.count
@CallCount
def hello(name):
print('Hello, {}'.format(name))
Output
hello.get_count()
Out[10]: 0
hello('d')
Hello, d
hello('a')
Hello, a
hello('b')
Hello, b
hello.get_count()
Out[14]: 3
Reference
- code url
Comments
Post a Comment