Decorators are like adding some additional behavior to an existing function. For example, you can measure the execution time and output it, or add a message such as "~ ~ function was executed".
This time, I made something to add a message to the output and execution time measurement Code created: https://github.com/KodairaTomonori/Qiita/tree/master/default_module/syntax
decoration.py
deco = '¡+゜+¡・゜・¡+*+¡・★・¡+*+¡・===[ '
deco_end = deco.replace('[', ']')[::-1]
deco_result = [' ∧____∧ Results', '( `Д´ )I will output', '(▄︻▇〓┳0035', '/ )', '( / ̄∪']
def deco_func(func):
def decoration(*args, **kwargs):
print(deco + 'start ' + func.__name__ + deco_end)
for i in range(len(deco_result) ):
if i != 2: print(deco_result[i])
else: print(deco_result[i], func(*args, **kwargs) )
print(deco + 'end ' + func.__name__ + deco_end)
return decoration
@deco_func
def addition(a, b):
return '{} + {} = {}'.format(a, b, a + b)
if __name__ == '__main__':
addition(103842, 283746)
The decorator is that the deco_func
function returns the decoration
function created within the function.
decoration
prints the beginning and end to decorate the output.
You can get the function name with func.__name__
.
Also, by setting (* args, ** kwargs)
, it is possible to correspond to most functions.
To use it as a decorator, just add @deco_func
in front of the function.
By doing this, ʻaddition =
deco_func (addition) (a, b) `.
timer.py
#usr/bin/python
import time
def timer(func):
def print_time(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
print(func.__name__ + \
'The time it took to execute{}Seconds'.format(time.time() - start) )
return print_time
@timer
def roop_timer(a):
return roop(a)
def roop(a):
sum_ = 0
for i in range(a):
sum_ += i
return sum_
if __name__ == '__main__':
roop_timer(10000)
timer(roop)(10000)
output.txt
roop_The time taken to execute the timer is 0.0008311271667480469 seconds
It took 0 time to execute roop.0008249282836914062 seconds
print_time
measures the time and outputs the result.
func.__name__
will fetch the function name.
If you want to reflect @ timer
only partially, you can do the same operation by settingtimer (roop) (10000)
.
It is also possible to create a function dedicated to it, such as roop_timer
(it is easier to create this when using two or more).
You can easily add other functions to a function by adding @decorate_function
.
Recommended Posts