J'étudie le décorateur et le wrapper en expérimentant des exemples et j'ai trouvé le comportement du décorateur que je ne comprends pas.python décorateur et wrapper fonction debug
def decorator_function(original_function):
def wrapper_function():
print "wrapper is executed before {}".format(original_function.__name__)
return original_function() # Try it without()
return wrapper_function
@decorator_function
def display():
print("display function ran!")
quand je lance au-dessus de la fonction:
In [59]: display()
wrapper is executed before display
display function ran!
Cependant, lorsque je déplace la fonction d'impression à l'extérieur de l'emballage, il semble que l'emballage ne fonctionne pas du tout. (Probablement il a couru, mais je ne vois pas la preuve.)
def decorator_function(original_function):
def wrapper_function():
#print "wrapper is executed before {}".format(original_function.__name__)
return original_function() # Try it without()
print "wrapper is executed before {}".format(original_function.__name__)
return wrapper_function
@decorator_function
def display():
print("display function ran!")
Alors je ne vois pas « wrapper est exécuté avant ... » plus. Comment venir? Qu'est-ce qui me manque ici?
In [63]: display()
display function ran!
Plus précisément, "wrapper est exécuté" est imprimé au moment où 'display' est défini (c'est-à-dire quand' decorator_function' est réellement exécuté). – chepner