3

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.

2
  • 1
    Why use getattr here? Commented Oct 16, 2013 at 15:53
  • I think the question is given aboundMeth (regardless of how it obtained its value), what is a/the name associated with the bound method object. Using aBoundMeth = Aobj.a would not affect the answer. Commented Oct 16, 2013 at 16:05

1 Answer 1

9

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

3 Comments

Thanks. I was wondering why it's impossible to see _name_ using dir(aBoundMeth)
@user1264304 - "Note Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names" - docs.python.org/3/library/functions.html#dir
dir gets it's its info from __dict__. If you actually look at a function object's __dict__. If you look at the function object's dict, it is empty -- So python must be doing some sort of special __getattr__ magic within the interpreter to give you the name.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.