0

I need to pass an instance method as an argument to a function:

class C(object):
    def m(self):
        print("m",self)

def f(l,b):
    for z in l:
        b(z)

x = C()

f([x], lambda c: c.m())

is there a better way than the lambda?

It appears that f([x], C.m) works too, but is this an accident or an official feature?

2
  • 3
    C.m will be a reference to an unbound method (as in no associated self instance). Passing <instance>.m would work though. Commented Jun 10, 2018 at 4:44
  • @jedwards: I do not have the instance. Commented Jun 10, 2018 at 4:48

2 Answers 2

2

You can do this:

f([x], C.m)

Here, C.m is the method without an instance. It does the same thing as your lambda. It is definitely an official and supported feature.

Sign up to request clarification or add additional context in comments.

Comments

1

operator.methodcaller

>>> from operator import methodcaller
>>> f([x], methodcaller('m'))
m <__main__.C object at 0x1317bbda0>

methodcaller returns a callable that will call a method on a given instance passed to it.

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.