Advanced Functional Programming with Callable Objects in Python
Lesson Introduction
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.
Setting Up
We start by defining a class for employees:
This class holds basic details about an employee, which include their name and salary.
Defining a Functional Object
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.
Using Functional Objects in a Program
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:
Applying the Callable with List Comprehension
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.
