Hello and welcome! Today's lesson explores a powerful feature of Python: storing functions in variables. This is useful for scenarios like callbacks, event handlers, or flexible program design. Our goal is to understand how to do this in Python.
By the end of this lesson, you'll know how to store functions in variables and utilize them effectively in your code.
Most importantly, we will learn how to treat objects as functions using callable objects, which will be very useful in future lessons.
First, let's explore how Python treats functions as first-class objects. This means you can assign functions to variables, pass them as arguments to other functions, and return them from other functions.
Consider a function to add two integers:
Python1def add(a, b): 2 return a + b 3 4if __name__ == "__main__": 5 print(add(1, 3)) # Output: 4
To store this function in a variable:
Python1def add(a, b): 2 return a + b 3 4if __name__ == "__main__": 5 # Assign the function to a variable 6 fp = add 7 8 # Use the function stored in the variable 9 print("Using function stored in variable:", fp(2, 3)) # Output: Using function stored in variable: 5
Here, fp = add
assigns the function add
to the variable fp
. We then call fp(2, 3)
to use the add
function through the variable fp
.
Functions in Python are first-class objects because they can be passed around as arguments, returned from other functions, and assigned to variables. This makes them very flexible and powerful for dynamic behavior in your programs. In this lesson, we will cover ways of assigning a function to a variable. In the subsequent lessons you will learn about designing the higher-order functions which work with other functions as inputs or return values.
Next, let's recall lambda expressions, a compact way to create small anonymous functions at runtime. Lambdas are particularly useful when you need a simple function for a short period.
Here's a comparison using a lambda function for the same add
operation:
Python1# Using lambda expression 2add_lambda = lambda a, b: a + b 3 4if __name__ == "__main__": 5 print("Using lambda expression:", add_lambda(2, 3)) # Output: Using lambda expression: 5
Here, add_lambda = lambda a, b: a + b
creates an anonymous function that adds two numbers and assigns it to the variable add_lambda
.
Lambda expressions offer a concise way to define simple functions but should be used when the function's logic is straightforward and doesn't require extensive statements or complexity.
Additionally, Python allows classes to define objects that can be called as functions. This is done by implementing the __call__
method in a class.
Here's an example of a callable object:
Python1class Adder: 2 def __call__(self, a, b): 3 return a + b 4 5if __name__ == "__main__": 6 # Create an instance of Adder 7 adder = Adder() 8 9 print("Using callable object:", adder(2, 3)) # Output: Using callable object: 5
Here, the class Adder
has a __call__
method defined, allowing its instances to be called like a regular function.
- Callable Object: Defining
__call__
in a class makes its instances behave like a function. - Using Callable Object:
print("Using callable object:", adder(2, 3))
calls the__call__
method on theadder
instance, giving the result5
.
Callable objects provide a way to encapsulate complex functionality in an object while retaining the ability to call it just like a function. We will explore the callable objects and related design patterns in the future courses of this path.
We explored how to store functions in variables using Python's first-class functions. We learned:
- Functions as First-Class Objects: You can assign functions to variables
- Lambda Expressions: Provide a concise way to define simple, anonymous functions.
- Callable Objects: Allow class instances to behave like functions by implementing the
__call__
method.
In the next lessons, we are going to learn how to use functions as input or return values of other functions.
These features make Python a very flexible and powerful language for dynamic and functional programming. Now that you understand the theory and practical aspects, it's time for practice. In the next set of exercises, you'll try storing and using functions in variables using these methods. This hands-on practice is crucial to solidify your understanding. Let's get started!