Nan Hua
Nan Hua

Reputation: 3694

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

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, ..)?

Upvotes: 4

Views: 1925

Answers (2)

zvone
zvone

Reputation: 19362

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)

Upvotes: 3

TheLazyScripter
TheLazyScripter

Reputation: 2665

Hopefully this explains it!

class T(object):
    def m1(self, a):
        return a
f=T().m1 #must initialize the class using '()' before calling a method of that class
f(1)

f = T()
f.m1(1)

f = T().m1(1)

f = T
f().m1(1)

f = T.m1
f(T(), 1) #can call the method without first initializing the class because we pass a reference of the methods class

f = T.m1
f2 = T()
f(f2, 1)

Upvotes: 0

Related Questions