This is a topic that I keep encountering but have struggled to fully grasp. To be fair I haven't looked too deeply into it. And now I am doing so. Python-course has a great article on the topic. They really go step by step. I've summarised what was in the article and re-written it in a way I understand it better.
A few notes about Python functions:
- Function names are references to functions and you can assign multiple names to the same function
e.g. def func(x):
return x
func2 = func
==>> Calling either func2(4) or func(4) would give the same output as they are just references to the same function
- Functions can be nested inside functions. I have done this a handful of times.
- Functions can accept other functions as arguments.
- Functions can return functions
These features are important in understanding how a decorator works. A decorator allows you to add additional features to functions by modifying them.
Basic example of how a decorator works by python-course. |
Here the function foo is wrapped in our_decorator which changes the way foo works. The above code block is essentially equivalent to the code below. It shows us what's happening "behind the scenes" when we use a @decorator.
So essentially, we call the decorated function which is then passed to the decorator as an argument. The decorator does whatever it wants to it, and returns a modified object. I can't wait to try playing around with decorators now Though I'm not entirely certain what context I would use it in.
Comments
Post a Comment