+ 1
Can somebody explain decorators for me pliz in python
2 Réponses
+ 2
Decorators are wrappers around functions, methods, and classes. Typically they add some functionality to the wrapped code but they can also be used to simply modify parameters or do some logging. Here's a simple example:
import time
def time_call(func):
def _wrapper(*args, **kwargs):
current_time = time.time()
func(*args, **kwargs)
elapsed_time = time.time() - current_time
print('Elapsed time: {}'.format(elapsed_time))
@time_call
def my_func(sec):
time.sleep(sec)
my_func(2)
# prints 'Elapsed time: 2000'
This is a simple example and there's way more you can do. This is a very powerful feature when used right.
+ 2
Here is an example of what a decorator may be useful for:
https://code.sololearn.com/cD09ijlIS6Ev/?ref=app