Calling methods without objects?
Steve D'Aprano
steve+python at pearwood.info
Mon Sep 25 21:17:21 EDT 2017
On Tue, 26 Sep 2017 08:49 am, Stefan Ram wrote:
> So, is there some mechanism in Python that can bind a method
> to an object so that the caller does not have to specify the
> object in the call?
Indeed there is.
Methods (like functions) are first-class values in Python, so you can do:
py> finder = "Hello World!".find
py> finder("W")
6
We say that `finder` is a bound method, meaning that it is a method object that
already knows the instance to operate on.
Python also has unbound methods: method objects that don't know the instance to
operate on, and so the caller has to provide it:
py> unbound_finder = str.find
py> unbound_finder("Goodbye for now", "f")
8
In Python 2, both bound and unbound methods were implemented as the same
underlying type, namely a thin wrapper around a function. In Python 3, unbound
methods no longer use the wrapper, and just return the function object itself.
The wrapper can be found in the types module:
from types import MethodType
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list