Reputation: 1015
I have a method which return its own name. The method looks like this:
import inspect
class example(object):
def getvalue(self):
return inspect.stack()[0][3] #returns current method's name
Now I am creating a method dyamically in that example class like this.
import inspect
class example(object):
def getvalue(self):
return inspect.stack()[0][3] #returns current method's name
if __name__=="__main__":
e = example()
e.method=e.getvalue
print e.method()
This gives the output getvalue. Now I want my getvalue() method to return dynamic method I created's name i.e method. Is there a way to do it in python? If so what changes do I have to do in my getvalue() method so that it returns dynamically created method's name.
import inspect
class example(object):
def getvalue(self):
return inspect.stack()[0][3] #what to write here...
Upvotes: 1
Views: 77
Reputation: 114491
This is not possible.
In Python the very same object can have multiple "names" and thus it doesn't make sense to talk about "the" name of an object.
Methods are objects and the compiler for functions and methods stores the "name" found when the compiling was done in a __name__
field. If you later move the object around and place it in places reachable using other names the __name__
field it has won't change.
Upvotes: 4