Back to articles
Quark's Outlines: Python Emulating Callable Objects

Quark's Outlines: Python Emulating Callable Objects

via Dev.to TutorialMike Vincent

Quark’s Outlines: Python Emulating Callable Objects Overview, Historical Timeline, Problems & Solutions An Overview of Python Emulating Callable Objects What does it mean to make a Python object callable? 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. Why would you make a Python object callable?

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles