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 functions1class Multiplier: # The constructor receives the factor to multiply by2 def __init__(self, factor): # Store the factor on the instance3 self.factor = factor4 # __call__ runs when the instance itself is called: obj(value)5 def __call__(self, value): # Return the value multiplied by the stored factor6 return value * self.factor7 # Create a Multiplier with factor 2; double is an object, not a function8double = Multiplier(2)# double(5) calls double.__call__(5), which returns 5 * 2 = 109print(double(5))Output
10
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