
Je vous propose un tutoriel introduction aux décorateurs Python.
Bonne lecture

Une erreur dans cette actualité ? Signalez-le nous !
Code : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def mon_decorateur(fonction): def ma_fonction_decoree(): """ma fonction décorée """ print(fonction.__name__ + ' appelée') fonction() return ma_fonction_decoree @mon_decorateur def ma_fonction(): """ma fonction affiche hello world """ print("hello_world") if __name__ == "__main__": ma_fonction() |
Code : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def mon_decorateur(fonction): def ma_fonction_decoree(): """ma fonction décorée """ print(fonction.__name__ + ' appelée') fonction() ma_fonction_decoree.__name__ = fonction.__name__ ma_fonction_decoree.__doc__ = fonction.__doc__ return ma_fonction_decoree @mon_decorateur def ma_fonction(): """ma fonction affiche hello world """ print("hello_world") if __name__ == "__main__": ma_fonction() |
Code : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import functools # Higher-order functions and operations on callable objects def mon_decorateur(fonction): @functools.wraps(fonction) def ma_fonction_decoree(): """ma fonction décorée """ print(fonction.__name__ + ' appelée') fonction() return ma_fonction_decoree @mon_decorateur def ma_fonction(): """ma fonction affiche hello world """ print("hello_world") if __name__ == "__main__": ma_fonction() |
Code : | Sélectionner tout |
1 2 3 4 5 | # update_wrapper() and wraps() are tools to help write # wrapper functions that can handle naive introspection WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__qualname__', '__doc__', '__annotations__') |
Code : | Sélectionner tout |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import functools # Higher-order functions and operations on callable objects def convert_args(*types_args, **kw): def decorator(func): @functools.wraps(func) def newf(*args): """newf""" return func(*(type_arg(arg) for arg, type_arg in zip(args, types_args))) return newf return decorator @convert_args(float, int, str, lambda x:x+1) def function(*args): """Hello """ return [0, ] + list(args) print(function(1, 2, 3, 4)) # [0, 1.0, 2, '3', 5] |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |
![]() |