7

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

chrise
  • 4,039
  • 3
  • 39
  • 74

2 Answers2

7

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
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Thanks Ashwini. For the function, I am looking for a way to print the name without spepcifying the function. Edited my question to explain what my purpose is – chrise Jun 19 '13 at 16:33
3

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)

Community
  • 1
  • 1
rickcnagy
  • 1,774
  • 18
  • 24