Back to list
クアルクのサマリー:ポインタによってカスタマイズされたCallableなオブジェクト
Quark's Outlines: Python Emulating Callable Objects
Translated: 2026/3/7 13:05:29
Japanese Translation
クアルクのサマリー:ポインタによってカスタマイズされたCallableなオブジェクト
概要、歴史タイムライン、問題及び解決策
Pythonで括弧をつけて使うと、それがある意味では関数が呼ばれています。しかし、あなたは自身のオブジェクトを関数として引き受けれるようにするためだけでもあります。クラスに名前 __call__ を定義することで、クォアルクは何が見つかることも可能です」
Pythonのcallableなオブジェクトは、括弧と引けます。そして、それについてパラメータを持つものを指します。これは関数、メソッド、そしてその何らかの呼び出しを定義している __call__ メソッドがあるオブセグメントに達します。
クォアルクではあなたが自身のオブジェクトをcallable なオブジェクトに設定することも可能です。これを行うために__call__()メソッドを使います。(__call__()メソッドはありませんと、それにも事前に対応します。)__
次のようなクラスを作ります。
クラス Greeter:
def __call__(self, name):
return f'Hello, {name}!'
そして,次のようにグレーターオブジェクトが使用することができます。
グリート = グリーター('アダ')
print(グリート())
# プリンティング:
# Hello, アダ!
ここでグリートは機能していないが、括弧をつけて引けると__call__()メソッドの動作に従うためです。
オブジェクトは何かとして状態を持つことはできます。そうすることであなたは前の入力、設定などについてそれを持っていることができます。
Callableなオブジェクトを使用するときがある場合もあります。(その中で新たなオブジェクトによる状態を管理することも可能です)
Pythonにおける__call__がどのように導入されるか
Pythonの __call__()メソッドにより、行いながらデータとロジックを一つにまとめることができる概念が、言語のObject Orientedシステムにあります。小 talks という 70年代のメッセージパッシングは「関数の呼び出し」がただオブジェクトに対する「メッセージ送信」となることを概念として設定しました。
それの先には Lisと Schemeにおける closures があることにより、BehaviorとMemoryを一緒に運ぶことが出来ます。また、この __call__メソッドもPythonそのものが導入したものです。その導入は0.9.0です。
Callableなオブジェクトは状態を持ち、そしてそれが関数として見えることが出来ます。
クラスカウンターを作ります。そして次のように実行します。
定義:
Counter()
def __init__(self):
self.total = 0
def __call__(self, amount):
self.total += amount
return self.total
そしてそれを使いましょう。
これがあなたのかかれるオブジェクトについて動作している様子となります:
add = コンター()
print(add(5))
# プリント:
# 5
またここに、addは実際に__call__()メソッドを使って関数の動作をすることが出来ます。
問題:一つのオブジェクトがあるときに何が起るのであろうか。
答え: __call__()メソッドをクラスインスタンスの中に組み込むことで解決することができます。
ここにまた類似のオブジェクトがあります。
クラストラッカーを作ります、そして次のようにします。
def __init__(self):
self.calls = 0
def __call__(self):
self.calls += 1
return self.calls
ここでトラックしたオブジェクトが実際に状態を維持し、それに応答することで動作することができます。
問題:何が解決するか。オブジェクトのカウンタを作ります。
回答: __call__()メソッドの中に状態を持ち出しています。(そしてそれを__call()に組み込んで)
このコードはオブジェクトを呼び出すと、それにはカスタムが適用されるかもしれません。それに応答したときに何が起こるのかどうかは、それは__call__()メソッドの動作次第です。
Original Content
Quark’s Outlines: Python Emulating Callable Objects
Overview, Historical Timeline, Problems & Solutions
When you use parentheses in Python, you are usually calling a function. But you can also make your own objects behave like functions. If you define a method called __call__ inside your class, then Python will let you “call” an instance of that class as if it were a function.
A Python callable object is any object that can be followed by parentheses and arguments. This includes functions, methods, and any object that defines a __call__() method.
Python lets you make your own objects callable by adding __call__.
class Greeter:
def __call__(self, name):
return f"Hello, {name}!"
greet = Greeter()
print(greet("Ada"))
# prints:
# Hello, Ada!
Even though greet is not a function, calling it with ("Ada") runs its __call__ method.
You make objects callable when you want them to act like functions but also hold some state. This is helpful when you want an object that remembers past input, has configuration settings, or behaves differently based on how it was set up.
A callable object can replace a function when you need more control or context.
Python callable objects can hold state and act like functions.
class Counter:
def __init__(self):
self.total = 0
def __call__(self, amount):
self.total += amount
return self.total
add = Counter()
print(add(5))
print(add(10))
# prints:
# 5
# 15
Here, the object add behaves like a function but also remembers its internal total.
Where does Python’s callable object behavior come from?
Python's idea of treating anything with a __call__() method as a function follows from object-oriented systems that treat behavior as part of the object. It lets you combine data and logic into one thing.
1970s — Message-passing in Smalltalk inspired the idea that calling a function is just sending a message to an object.
1980 — Function objects in Lisp and Scheme let closures carry behavior and memory together.
1991 — Python introduced __call__() in version 0.9.0, making objects with __call__ act like functions.
2001 — Callable check added with the built-in callable() function to test whether an object can be called.
2025 — Callable objects used in decorators and factories in most modern Python programs for extensibility.
How do you use Python callable objects the right way?
Python callable objects help you build tools that act like functions but do more. You can store state, wrap behavior, or customize how things respond to input. These problems show when and how to define __call__() in Python classes.
You are building a tool that should be used like a function, but it also needs to store settings. You want the object to accept input with parentheses, but you also want to keep track of how it was set up.
Problem: You want an object to respond to calls like a function.
Solution: Define a __call__() method inside the class.
Python lets you make objects callable by defining __call__.
class Adder:
def __init__(self, n):
self.n = n
def __call__(self, x):
return x + self.n
add_five = Adder(5)
print(add_five(10))
# prints:
# 15
The object add_five now works like a function. It uses the stored number when called.
You want to create an object that counts how many times it is used. You want it to return the count each time it runs. A regular function does not keep track of state unless you use global variables or extra code.
Problem: You want your callable to remember past values.
Solution: Store state in attributes, and update them in __call__.
Python lets you build stateful callables using class attributes.
class Tracker:
def __init__(self):
self.calls = 0
def __call__(self):
self.calls += 1
return self.calls
count = Tracker()
print(count())
print(count())
# prints:
# 1
# 2
This object remembers how many times it has been called.
You are refactoring your code. A simple function is growing too complex. You want to turn it into a class that behaves the same way, so old code still works.
Problem: You need an object that acts like the function it replaced.
Solution: Define a class with __call__() and use it in place of the old function.
Python lets you swap functions for callables with the same signature.
class Square:
def __call__(self, x):
return x * x
f = Square()
print(f(6))
# prints:
# 36
The object f works like a function and can be passed anywhere a function is expected.
You want to build a tool that behaves differently based on how it was created. Each instance should run the same kind of logic but with different settings.
Problem: You want to control the behavior of each callable object.
Solution: Pass setup data to __init__() and use it in __call__().
Python lets you configure callable behavior using instance state.
class Greeter:
def __init__(self, greeting):
self.greeting = greeting
def __call__(self, name):
return f"{self.greeting}, {name}!"
hi = Greeter("Hi")
hello = Greeter("Hello")
print(hi("Ada"))
print(hello("Bob"))
# prints:
# Hi, Ada!
# Hello, Bob!
Each object behaves like a different function but follows the same class pattern.
You have a mix of objects. Some are functions. Some are numbers. You want to run the ones that can be called, but skip the others. You need a safe way to check.
Problem: You want to test if an object can be used with parentheses.
Solution: Use Python’s built-in callable() function.
Python lets you check if an object is callable.
def f(): return 42
class C: pass
obj = C()
print(callable(f))
print(callable(obj))
# prints:
# True
# False
If the object defines __call__, callable() returns True. If not, it returns False.
Did you find this helpful? Let me know by clicking the like button below. I'd love to hear your thoughts in the comments, too! If you want to see more content like this, don't forget to subscribe. Thanks for reading!
Mike Vincent is an American software engineer and app developer from Los Angeles, California. More about Mike Vincent