This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| python:decorators [2024/08/31 10:55] – Niels | python:decorators [2024/09/30 08:09] (current) – Niels | ||
|---|---|---|---|
| Line 2: | Line 2: | ||
| Decorators extend functions, methods, classes without explicitly modifying the code of the item being decorated. | Decorators extend functions, methods, classes without explicitly modifying the code of the item being decorated. | ||
| + | |||
| + | example of a decorator //Italic (skelleton structure only)//: | ||
| + | |||
| + | <code python> | ||
| + | def decorator_function(func): | ||
| + | ''' | ||
| + | | ||
| + | def actual_decorator(*args, | ||
| + | ''' | ||
| + | | ||
| + | # do something, before original logic | ||
| + | | ||
| + | #call the original function | ||
| + | func(*args, | ||
| + | | ||
| + | # and/or do something after. | ||
| + | | ||
| + | #return result | ||
| + | | ||
| + | #return the actual decorator so it gets called by calling context . | ||
| + | return actual_decorator | ||
| + | |||
| + | </ | ||
| + | |||
| + | example of decorator with arguments// | ||
| + | |||
| + | <code python> | ||
| + | def decorator_function(a, | ||
| + | ''' | ||
| + | | ||
| + | def additional_wrapper(func): | ||
| + | ''' | ||
| + | | ||
| + | def actual_decorator(*args, | ||
| + | ''' | ||
| + | | ||
| + | #arguments a and b passed from outer fuction are in scope but read only. | ||
| + | if a > b: | ||
| + | | ||
| + | # do something, before original logic | ||
| + | | ||
| + | #call the original function | ||
| + | func(*args, | ||
| + | | ||
| + | # and/or do something after. | ||
| + | | ||
| + | #return result | ||
| + | | ||
| + | # return function to calling context (so that it gets executed). | ||
| + | return actual_decorator | ||
| + | |||
| + | #return fuction to calling context (so that it gets executed). | ||
| + | return additional_wrapper | ||
| + | </ | ||
| Line 9: | Line 63: | ||
| *[[https:// | *[[https:// | ||
| *[[https:// | *[[https:// | ||
| - | * [[https:// | + | *[[https:// |
| + | *[[https:// | ||
| + | *[[https:// | ||
| {{tag> | {{tag> | ||