Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Callable Objects and __call__

Learn how Python instances become callable with __call__, including state, arguments, return values, and inheritance.

Levels: Advanced ~22 min read

Advanced

Python objects can be made callable by defining `__call__()`. That gives an instance function-like call syntax while allowing the object to carry state, configuration, and other behavior.

Make an instance callable

When an instance is followed by parentheses, Python can call its `__call__()` method. The method receives the instance as `self`, just like another instance method.

python
1
2
3
4
5
6
class Greeter:
    def __call__(self, name):
        return f"Hello, {name}!"

greet = Greeter()
print(greet("Mina"))

Defining `__call__()` makes a `Greeter` instance callable. The expression `greet("Mina")` invokes the method and returns its result.

Use normal argument rules

`__call__()` is a method, so its parameter list follows the normal function and method calling rules you already learned.

python
1
2
3
4
5
6
7
8
9
class Calculator:
    def __call__(self, left, right, /, *, operation="add"):
        if operation == "add":
            return left + right
        return left - right

calculate = Calculator()
print(calculate(7, 2))
print(calculate(7, 2, operation="subtract"))

A callable instance can use ordinary function parameter features, including positional-only and keyword-only parameters.

Keep state between calls

A callable instance can store state on `self`. This is a major reason to choose a callable object over a plain function when the operation has persistent configuration or state.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Counter:
    def __init__(self, start=0):
        self.value = start

    def __call__(self):
        self.value += 1
        return self.value

counter = Counter(10)
print(counter())
print(counter())
print(counter.value)

A callable object can keep state on itself, so separate calls can observe and update the same attribute.

Check whether an object is callable

The built-in `callable()` returns `True` when its argument is callable and `False` otherwise.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def square(number):
    return number * number

class Greeter:
    def __call__(self, name):
        return f"Hello, {name}!"

greet = Greeter()
print(callable(square))
print(callable(greet))
print(callable(42))

The built-in `callable()` reports whether an object is callable. Functions and objects with `__call__()` return `True` here.

Return values normally

`__call__()` can return any value, just like another method. The surrounding call expression receives that returned value.

python
1
2
3
4
5
6
7
class Formatter:
    def __call__(self, value):
        return f"[{value.upper()}]"

format_value = Formatter()
result = format_value("ready")
print(result)

The value of `obj(...)` is the value returned by `__call__()`, unless the call raises an exception.

Give each object independent configuration

Each callable instance can carry different state or configuration while sharing the same implementation.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Prefixer:
    def __init__(self, prefix):
        self.prefix = prefix

    def __call__(self, message):
        return f"{self.prefix}: {message}"

warning = Prefixer("Warning")
info = Prefixer("Info")
print(warning("Low disk space"))
print(info("Backup complete"))

Separate instances can carry different configuration while sharing the same callable implementation.

Use inheritance normally

`__call__()` participates in ordinary method inheritance. A subclass can override it, inherit it, or extend a base implementation with `super()`.

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Operation:
    def __call__(self, value):
        return value + 1

class DoubleOperation(Operation):
    def __call__(self, value):
        return super().__call__(value * 2)

operation = DoubleOperation()
print(operation(4))

`__call__()` is a normal special method for inheritance. A subclass can override it and use `super()` to continue with inherited behavior.

Know when a named method is clearer

Making an object callable is not automatically better. Use it when the object naturally represents one primary operation. When an object exposes several distinct actions, named methods can make the interface clearer.

python
1
2
3
4
5
6
class PriceCalculator:
    def tax(self, amount):
        return amount * 0.20

calculator = PriceCalculator()
print(calculator.tax(100))

A callable instance is useful when the object itself represents one primary operation. Named methods can be clearer when an object exposes several distinct actions.

A callable object is still an ordinary object: it can have attributes, other methods, inheritance, and state. Call syntax is simply an additional interface supplied by `__call__()`.

Key takeaways

  • Defining __call__() makes instances of the class callable with function-like syntax.
  • The __call__() method follows ordinary method argument and return-value rules.
  • Callable objects can combine one primary operation with persistent state or configuration.
  • callable() can report whether an object is callable; an instance with __call__() is callable.
  • __call__() participates in normal inheritance, so subclasses can override or extend call behavior.
Was this page helpful?

Mark this learning resource complete to track your learning progress.