callable
In Python, a callable is any object that you can call like a function. This means you can use parentheses () to invoke the object and possibly pass arguments to it.
Functions, methods, and classes are callable. Calling a class creates a new instance. However, other objects can be made callable by implementing the .__call__() special method. This method allows you to create objects that behave like functions.
You can check if an object is callable using the built-in callable() function, which returns True if the object appears callable and False otherwise. A True result doesn’t guarantee that a call will succeed, but a False result means the call will always fail.
Understanding the concept of callables is essential when working with higher-order functions, decorators, and any Python feature that requires passing around functions or function-like objects.
Example
Here’s an example demonstrating a class with the .__call__() method, making its instances callable:
adder.py
class Adder:
def __init__(self):
self.value = 0
def __call__(self, value):
self.value += value
return self.value
# Usage
adder = Adder()
adder(10) # Output: 10
adder(10) # Output: 20
adder(10) # Output: 30
In this example, Adder is a class whose instances are callable. They add any passed value to the .value attribute.
Related Resources
Tutorial
Python's .__call__() Method: Creating Callable Instances
In this tutorial, you'll learn what a callable is in Python and how to create callable instances using the .__call__() special method in your custom classes. You'll also code several examples of practical use cases for callable instances in Python.
For additional information on related topics, take a look at the following resources:
- Create Callable Instances With Python's .__call__() (Course)
- Primer on Python Decorators (Tutorial)
- Python Built-in Functions: A Complete Guide (Tutorial)
- Python's .__call__() Method: Creating Callable Instances (Quiz)
- Python Decorators 101 (Course)
- Primer on Python Decorators (Quiz)
- Exploring Python's Built-in Functions (Course)
- Python Built-in Functions: A Complete Guide (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.