surfandro
0
Q:

python creare decoratori

# Decorator with arguments
import functools

# First function takes the wanted number of repetition
def repeat(num_times):
    # Second function takes the function
    def decorator_repeat(func):
        # Third function, the wrapper executes the function the number of times wanted        
        # functools decorator to print the true name of the function passed instead of "wrapper"
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result= func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

# Our function using the decorator
@repeat(num_times= 3)
def greet(name):
    print(f"Hello {name}")

greet("thomas")
2
#Decorator are just function that take function as first
#parameter and return a function
def logging(f):
  def decorator_function(*args, **kwargs):
    print('executing '+f.__name__)
    return f(*args, **kwargs)
  return decorator_function
#Use it like this
@logging
def hello_world():
  print('Hello World')
#calling hello_world() prints out:
#executing hello_world
#Hello World
3
@funzione_decoratore
def mia_funzione(): 
    print("Hello World!") 

mia_funzione()
# output:

... codice da eseguire prima di funzione_parametro ...
hello world!
... codice da eseguire dopo di funzione_parametro ...
0
def funzione_decoratore(funzione_parametro): 
    def wrapper(): 
        """ nome convenzionale - wrapper significa 'incarto, confezione' """
        print("... codice da eseguire prima di 'funzione_parametro' ...") 					
        funzione_parametro()
        print("... codice da eseguire dopo di 'funzione_parametro' ...") 
    return wrapper

def mia_funzione(): 
    print("Hello World!")
0
def mia_funzione(): 
    print("Hello World!") 
    
>>> print(mia_funzione.__name__)
mia_funzione
0
mia_funzione = funzione_decoratore(mia_funzione) 

mia_funzione()
# output:

... codice da eseguire prima di funzione_parametro ...
Hello World!
... codice da eseguire dopo di funzione_parametro ...
-1

New to Communities?

Join the community