Creating Callable Objects in Python

Lesson Introduction

Welcome to the lesson on creating callable objects in Python! In this session, we'll explore why callable objects are vital in modern Python programming. You'll learn how they encapsulate behavior within objects for more modular, reusable code. Our aim is to understand what callable objects are and how to create and use them through practical examples.

What Are Callable Objects?

Callable objects are objects you can call, like functions. Essentially, they encapsulate a function's logic within an object. This is particularly useful for passing functions as arguments, storing them, or configuring them with state information.

Unlike standard functions, which cannot hold state in an object-oriented manner, callable objects can maintain state because they are implemented through classes. This allows them to keep information across function calls, enabling more complex behavior than a simple function or lambda expression can provide.

Designing Callable Objects

Let's start by designing a basic class for our callable object. We'll set up an initializer for state initialization and define the __call__ method to make the object callable, like a function.

Consider creating a callable object to filter people based on age:

class OlderThan:
    def __init__(self, limit):
        self.limit = limit  # Initialize the age limit state

    def __call__(self, person):
        return person.age > self.limit  # Callable method that compares the person's age to the limit

Here:

  • The initializer __init__(self, limit) initializes the age limit state to a specified value.
  • The __call__(self, person) method makes the object callable, like a function and contains the logic to check if a person's age is greater than the limit.

Code Example Breakdown: Part 1

Now, let’s break down the callable objects and their supporting classes in a full example. First, define a class to represent a person:

class Person:
    def __init__(self, name, age):
        self.name = name  # Initialize the person's name
        self.age = age  # Initialize the person's age

    @property
    def name(self):
        return self._name  # Getter method for the name attribute

    @name.setter
    def name(self, value):
        self._name = value

    @property
    def age(self):
        return self._age  # Getter method for the age attribute

    @age.setter
    def age(self, value):
        self._age = value

This class has:

  • An initializer __init__(self, name, age) to initialize the person’s name and age attributes.
  • Properties name and age, to access these attributes, ensuring encapsulation.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal