Do you know about
This is a special method you can define on your Python class. It's optional. But def'ing it lets you hook into Python's function call syntax.
Let me explain. Look:
- class Prefixer:
- def __init__(self, prefix):
- self.prefix = prefix
- def __call__(self, message):
- return self.prefix + message
You use it like this:
- >>> simonsays = Prefixer("Simon says: ")
- >>> simonsays("Get up and dance!")
- 'Simon says: Get up and dance!'
What's the type of "
If you look at just that last line of Python code, you'd think it's
a function. But it's not. It's an instance of
You with me so far?
Essentially, there's a translation step. When you write
simonsays('Shake it, baby!')", that's translated, in a
sense, to "
simonsays.__call__('Shake it, baby!')". In
other words, "
simonsays(" triggers a function call.
Also - check this out:
- >>> def increment(x):
- ... return x + 1
- >>> increment.__call__(2)
Surprise! Regular Python functions do this too!
What I want you to get is the difference between the python code you write, and what Python's runtime actually perceives.
When you write "
something", followed by "(", Python
itself processes that as "
something.__call__(". No matter
what "something" actually is.
This is a hint of what I mean by "seeing into the Matrix of Python".
You're starting to see what Python's runtime sees. Not just the Python code itself. Beneath that. To a level 99% of Python developers never realize is even there.
That's a FUN place to be. Pythonically dodging bullets and walking through walls. So to speak.
Our professional trainings range from $3,000 to $12,000. To find out if Powerful Python is right for you, schedule a 30-minute discovery call with our team here: