Python functions are first class citizens, which means that functions can be treated as objects.
- A function can be assigned to a variable, i.e. they can be referenced.
- A function can be passed as an argument to another function.
- A function can be returned from a function.
Decorators with parameters are similar to regular decorators.
Syntax for decorators with parameters
@decorator (params) def func_name (): ’’ ’Function implementation’’,
The above code is equivalent
def func_name (): ’’ ’Function implementation’’, func_name = (decorator (params)) (func_name) "" "
Since execution starts from left to right, the decorator (params) is called which returns the function object fun_obj . Using fun_obj, fun_obj (fun_name) . Inside the inner function, the necessary operations are performed and the actual reference to the function is returned, which will be assigned to func_name . Now func_name () can be used to call the function with applied m to it with a decorator.
The above code can be rendered step by step here
How Decorator is implemented with parameters
|
Here parameters can also be empty.
The above code can be rendered step by step here
example
|
Exit
Inside decorator Inside inner function I like pythonengineering Inside actual function
This example also tells us that the parameters of an outer function can be accessed using a nested inner function.
1. Inside the decorator
2. Inside the function
The above example can be rendered step by step here .
Note. Snapshots of images are taken with PythonTutor.