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
Access the name property on the object's constructor to get the class name of the object, e.g. obj.constructor.name . The constructor property returns a reference to the constructor function that created the instance object. Copied! We accessed the name property on the Object.
The name property of the Function object is used to get the function's name. name is a read-only property of the Function object.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With