Understand Python functions in-depth somewhat
Functions are objects
Everything in a Python program is represented by objects or relations between objects like strings, lists, modules, and functions are all objects.
This means a function can be assigned to a variable, just like any object.
Line no. 5 takes the function object referenced by say and creates a second name.
Speak is just another name for this function object, which means that you can delete the original name(Say) and still will be able to call the function through Speak.
Functions Can Be Stored in Data Structures
As we learned in the first section that functions are objects in Python, we can store them in data structure just like any other object. To access the function object stored inside let’s say a list would work something like this:
Functions Can Be Passed to Other Functions
This concept will be somewhat familiar if we are aware of delegates in c#. I was surprised when I first heard of this.
This way we can ensure that no function is left lonely. This way of passing function objects as arguments to other functions allows us to abstract away and pass around the behavior in our program. These functions that accept other functions as arguments are also called higher-order functions.
A good example would be the inbuilt function map() that takes an iterable and a function object as input, and then calls the function on each element in the iterable, yielding the results as it goes along.
Functions can return other functions
Functions can not only accept behaviors through arguments but they can also return behaviors.
Objects Can Behave Like Functions
All functions are objects but all objects are not functions. However, the objects can be made callable, which allows them to be treated like a function (in some cases). We can use the __call__ attribute for this purpose.
Not all objects will be callable though. There’s a built-in callable function to check whether an object appears to be callable or not.
Check out more such articles by me below, hope you learned something :)