It is actually 2 questions. 1) Is there a generic way to get the class name of an instance, so if I have a class
class someClass(object):
I would like a built in way that gives me a string 'someClass'
2) Similar with functions. If I have
def someFunction():
....
print builtinMethodToGetFunctionNameAsString
return
it would print 'someFunction'
The reason why I am looking for this is, that I have a bit of a jungle of classes and subclasses and for debugging I would like to print where I am, so to all methods I would just want to add something along the lines
print 'Executing %s from %s' %(getFunctionName,getClassName)
So I am looking for a generic command that know the class and the function where it is, so that I can copy and paste the line in all the methods without having to write a separate line for each of them
-
How about using a debugger?user395760– user3957602013年06月19日 16:50:36 +00:00Commented Jun 19, 2013 at 16:50
-
use .format instead of % 'Executing {} from {}'.format(getFunctionName, getClassName)Rafał Łużyński– Rafał Łużyński2013年06月19日 17:22:50 +00:00Commented Jun 19, 2013 at 17:22
2 Answers 2
use the __name__ attribute:
Class:
>>> class A:pass
>>> A.__name__
'A'
>>> A().__class__.__name__ #using an instance of that class
'A'
Function:
>>> def func():
... print func.__name__
...
>>> func.__name__
'func'
>>> func()
func
A quick hack for classes will be:
>>> import sys
>>> class A():
... def func(self):
... func_name = sys._getframe().f_code.co_name
... class_name = self.__class__.__name__
... print 'Executing {} from {}'.format(func_name, class_name)
...
>>> A().func()
Executing func from A
1 Comment
the function part has already been answered at this SO post. The code would be:
import sys
print sys._getframe().f_code.co_name
For the class part, use: A.__name__ or A().__class__.__name (for an instance)