rokpoto.com
rokpoto.com

Reputation: 10728

Get name of the bound method from instance of the bound method object in Python

I have :

class A:
    def a():
       pass

After typing in the python command line:

Aobj = A()
aBoundMeth = getattr(Aobj, 'a')

My goal is to get the name of the method that aBoundMeth object represents. Is it possible to do it? Thank you in advance.

Upvotes: 3

Views: 4460

Answers (1)

mgilson
mgilson

Reputation: 309861

Assuming that the name of the method is the string 'a' (in this case), You can use the __name__ attribute on the function object.

e.g.

>>> Aobj = A()
>>> aBoundMeth = getattr(Aobj, 'a')
>>> aBoundMeth.__name__
'a'

Note that this is the function name when it was created. You can make more references to the same function, but the name doesn't change. e.g.

>>> class A(object):
...     def a(self):
...        pass
...     b = a
... 
>>> Aobj = A()
>>> Aobj.a.__name__
'a'
>>> Aobj.b.__name__
'a'

Upvotes: 9

Related Questions