4

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

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

You can also use the @staticmethod decorator
@RafazZ If you used @staticmethod you would have different behaviour. The function would not have a self argument. Here, m1 receives a self in each of the three cases I wrote. If self is not used within m1, then yes - @staticmethod would be the preferred solution.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.