“Exemplos de decoradores de funções em Python” Respostas de código

Exemplos de decoradores de funções em Python

from functools import wraps

def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logit
def addition_func(x):
   """Do some math."""
   return x + x


result = addition_func(4)
# Output: addition_func was called
Vast Vulture

Exemplos de decoradores de funções em Python

from functools import wraps

def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # Open the logfile and append
            with open(logfile, 'a') as opened_file:
                # Now we log to the specified logfile
                opened_file.write(log_string + '\n')
            return func(*args, **kwargs)
        return wrapped_function
    return logging_decorator

@logit()
def myfunc1():
    pass

myfunc1()
# Output: myfunc1 was called
# A file called out.log now exists, with the above string

@logit(logfile='func2.log')
def myfunc2():
    pass

myfunc2()
# Output: myfunc2 was called
# A file called func2.log now exists, with the above string
Vast Vulture

Respostas semelhantes a “Exemplos de decoradores de funções em Python”

Perguntas semelhantes a “Exemplos de decoradores de funções em Python”

Mais respostas relacionadas para “Exemplos de decoradores de funções em Python” em Python

Procure respostas de código populares por idioma

Procurar outros idiomas de código