Hello! In our journey through functional programming, we've explored currying, partial application, and callable objects. Today, we'll dive into an advanced example using callable objects in combination with Python's powerful higher-order functions and list comprehensions. The goal is to deepen your understanding of how to create and utilize callable objects to make your code more modular and reusable, especially in a real-world context like adjusting employee salaries.
By the end of this lesson, you'll be able to create complex callable objects, apply them to collections using higher-order functions, and understand the benefits of such an approach.
We start by defining a class for employees:
This class holds basic details about an employee, which include their name and salary.
Let's create a callable class that increases salary by a certain factor:
In this example:
- The constructor
__init__(self, factor)initializes thefactorused to increase the salary. - The
__call__method takes anEmployeeobject and returns a newEmployeeobject with the updated salary.
Let's integrate the Employee class and the SalaryIncrease callable into a simple program. We need a collection of employees. We'll use a Python list:
To apply the 10% salary increase, we instantiate the SalaryIncrease callable:
We can apply our callable to each employee in the list using the map function:
The map function applies increase to each object in the employees list.
To print the results, we'll use a simple for loop:
In this code:
- The
forloop iterates over the transformed list. - We print each employee's name and new salary.
Here is the complete program demonstrating all the concepts:
To recap, in this lesson we've:
- Defined and utilized callable objects in Python to make our code more modular and reusable.
- Applied these callable objects to collections using list comprehensions to create elegant and readable code.
- Printed the results using a standard
forloop.
Now it's time to get hands-on practice. You'll move to practice sessions where you'll apply these concepts using your own IDE. This will help solidify your understanding and mastery of creating and using callable objects in Python. Happy coding!
