Callable Protocol in Python

Level 4162 keystrokes

This implements __call__ to make objects callable like functions. The Multiplier class can be called with parentheses.

Python code

# Define a class whose instances can be called like functions
1class Multiplier:
# The constructor receives the factor to multiply by
2 def __init__(self, factor):
# Store the factor on the instance
3 self.factor = factor
4
# __call__ runs when the instance itself is called: obj(value)
5 def __call__(self, value):
# Return the value multiplied by the stored factor
6 return value * self.factor
7
# Create a Multiplier with factor 2; double is an object, not a function
8double = Multiplier(2)
# double(5) calls double.__call__(5), which returns 5 * 2 = 10
9print(double(5))

Output

10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 8
  • (× 5
  • )× 5
  • :× 3
  • ,× 2
  • .× 2
  • =× 2
  • *× 1

More Python examples at level 4

← Python typing practice