Sometimes, we want to bind an unbound method with Python.
In this article, we’ll look at how to bind an unbound method with Python.
How to bind an unbound method with Python?
To bind an unbound method with Python, we can use the types.MethodType
method.
For instance, we write:
import types
def f(self):
print(self)
class C:
pass
meth = types.MethodType(f, C)
meth()
We have the f
function that prints the value of self
.
Then we set self
to C
by using types.MethodType(f, C)
and assign the returned function to meth
.
Therefore, when we call meth
, we see:
<class '__main__.C'>
printed.
Conclusion
To bind an unbound method with Python, we can use the types.MethodType
method.