In the following trivial example, what is the “Pythonic” way to create a “bound” method using some_method
and some_obj
? (Let us assume that we cannot just use some_obj.test_method
)
class Test:
def __init__(self, some_value):
self.some_value = some_value
def test_method(self, arg):
print(self.some_value, arg)
some_method = Test.test_method
some_obj = Test(1)
getattr(some_obj, some_method.__name__)
seems to do the trick – but this solution is not very elegant. One could also use a lambda, but in that case the arguments for the method except self
need to be specified.
Is there some simpler method to achieve this that I have overlooked?
kxl61 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Nothing wrong with what you’ve got, but you can also do
some_method.__get__(some_obj)
from types import MethodType
bound_method = MethodType(some_method, some_obj)
bound_method('argument')
When you call bound_method
, it passes some_obj
as the self
argument, similar to some_obj.test_method('argument')
.