Getting the object name and function name

Actually these are 2 questions. 1) Is there a general way to get the instance class name, so if I have a class

class someClass(object): 

I would like an inline way that gives me the string "someClass"

2) Similar to functions. if I have

 def someFunction(): .... print builtinMethodToGetFunctionNameAsString return 

it will print 'someFunction'

The reason I'm looking for this is because I have some jungle of classes and subclasses, and for debugging I would like to print where I am, so to all the methods I would just like to add something along the line

 print 'Executing %s from %s' %(getFunctionName,getClassName) 

So, I am looking for a general command that knows the class and function where it is, so that I can copy and paste the line into all methods without having to write a separate line for each of them

+6
source share
2 answers

use the __name__ attribute:

Grade:

 >>> class A:pass >>> A.__name__ 'A' >>> A().__class__.__name__ #using an instance of that class 'A' 

Functions:

 >>> def func(): ... print func.__name__ ... >>> func.__name__ 'func' >>> func() func 

A quick hack for classes would 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 
+5
source

part of the function has already been answered by this SO post . The code will look like this:

 import sys print sys._getframe().f_code.co_name 

For part of a class, use: A.__name__ or A().__class__.__name (for instance)

+3
source

Source: https://habr.com/ru/post/947668/


All Articles