Suppose we have the following code:
class T(object):
def m1(self, a):
...
f=T.m1
How to call f on an instance of T?
x=T()
x.f(..)?
f(x, ..)?
A member function is just like any other function, except it takes self as the first argument and there is a mechanism which passes that argument automatically.
So, the short answer is, use it ths way:
class T(object):
def m1(self, a):
pass
f=T.m1
x = T()
f(x, 1234)
This is because you are using T.m1, which is an "unbound method". Unbound here means that its self argument is not bound to an instance.
>>> T.m1
<unbound method T.m1>
Unlike T.m1, x.m1 gives you a bound method:
>>> x.m1
<bound method T.m1 of <__main__.T object at 0x0000000002483080>>
You can reference a bound method and use it without passing self explicitly:
f2 = x.m1
f2(1234)
partialYou can also do the equivalent "binding" self yourself, with this code:
import functools
unbound_f = T.m1
bound_f = functools.partial(unbound_f, x)
bound_f(1234)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With