Syntax
object.__call__(self[, args...])
The Python __call__
method makes a class callable, so you can call objects of the class like a normal function. For example, if you define __call__(self)
on an object x
of class X
, you can call it like so: x()
. The return value of the called object is the return value of the __call__()
method.
We call this a “Dunder Method” for “Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.
💡 Note: Formally, calling x(arg1, arg2, ...)
translates to type(x).__call__(x, arg1, ...)
whereas the type()
built-in function determines the class (type) of x
.
Minimal Example __call__
The following code snippet makes a custom class Person callable by providing an implementation of the magic method __call__()
that takes two arguments:
self
– a reference to the object itself. This is automatically passed into the function by Python—you don’t need to provide the argument yourself.other
– an additional argument (e.g., a string) to provide a custom greeting.
With this implementation, we can now create a callable object alice
and call it like so: alice()
.
class Person: def __call__(self, other): return f'Hi {other}' alice = Person() print(alice('Bob')) # Hi Bob
Background callable
Python’s built-in callable(object)
returns True
if you could call the object
argument like a function with the trailing parentheses in object()
.
You can make any object callable by implementing the instance’s __call__()
method.
For example, callable(callable)
returns True
because callable
is a function object. But callable(3)
returns False
because an integer is not a function you can call.
>>> callable(callable) True >>> callable(3) False
You can learn more about the function in our detailed blog guide:
References:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.