Transcript
A callable is an object that you can call.
Functions are callable objects
When you define a function in Python:
>>> def greet(name):
... print("Hi", name)
...
You'll get a function object:
>>> greet
<function greet at 0x7f61693c5940>
You can call a function object by putting parentheses (()
) after it:
>>> greet("Trey")
Hi Trey
So, functions are callables, meaning they're objects that you're able to call.
Is it a function or a class?
Functions are not the only callables in Python.
If we call the built-in enumerate
function, we will get back an enumerate
object:
>>> colors = ["green", "purple", "white", "pink"]
>>> enumerate(colors)
<enumerate object at 0x7f816c0ad400>
We can loop over that enumerate
object in order to see what's in it (related: looping with indexes):
>>> list(enumerate(colors))
[(0, 'green'), (1, 'purple'), (2, 'white'), (3, 'pink')]
Looping is the one thing we can do with an enumerate
object.
The reason we get back an enumerate
object when we call the enumerate
function, is that enumerate
isn't actually a function: it's a class!
>>> enumerate
<class 'enumerate'>
We call enumerate
a function because we often use the word "function" in a fuzzy way in Python.
In Python we think in terms of duck typing. So if something is a function-like object (meaning it acts like a function) we may simply call it "a function".
The built-in enumerate
function acts like a function (you call it using parenthesis) which means it's basically a function. But more properly, enumerate
is a callable, meaning it's an object that can be called.
In Python, functions can be called and classes can be called.
Callable class instances
Functions and classes are both callables, but you can actually invent your own callables too.
We have a class here called Person
:
class Person:
def __init__(self, name):
self.name = name
def __call__(self):
print("My name is", self.name)
When we call the Person
class:
>>> trey
<__main__.Person object at 0x7fbf9f3331c0>
We'll get back an instance of that class (a Person
object):
>>> trey = Person("Trey")
We can also call that Person
object by putting parentheses after it:
>>> trey()
My name is Trey
This works because we've implemented a __call__
method on the Person
class. Adding a __call__
to a class makes its class instances callable.
Summary
A callable is a function-like object, meaning it's something that behaves like a function. You can put parentheses after a reference to a callable to call it.
Functions are callables and classes are callables. They're not the only callables, but they're the primary two types of callables that you'll see in Python.
from Planet Python
via read more
No comments:
Post a Comment