Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a member function in python by its function instance?

Tags:

python

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, ..)?
like image 502
Nan Hua Avatar asked Oct 30 '25 16:10

Nan Hua


1 Answers

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)

Unbound Method

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>

Bound Method

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)

Bind using partial

You 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)
like image 184
zvone Avatar answered Nov 01 '25 06:11

zvone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!