| [ Web Proxy ] |
| Viewing: https://www.pythonbyexample.dev/examples/callable-objects | [Back] [Original] |
Data Model
A callable object starts as ordinary state stored on an instance.
Source
class Multiplier:
def __init__(self, factor):
self.factor = factor
self.calls = 0
double = Multiplier(2)
print(double.factor)Output
2__call__ makes the instance usable with function-call syntax.
Source
class Multiplier:
def __init__(self, factor):
self.factor = factor
self.calls = 0
def __call__(self, value):
self.calls += 1
return value * self.factor
double = Multiplier(2)
print(double(5))
print(double(7))Output
10
14Because the callable is still an object, it can remember state across calls.
Source
print(double.calls)Output
2Notes
callable(obj) checks whether an object can be called.10
14
2
Execution time appears here after you run the example.
| Web Proxy Viewer | New URL | Original Page |