getting object name and function name

前端 未结 2 983
被撕碎了的回忆
被撕碎了的回忆 2021-01-12 23:30

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):

相关标签:
2条回答
  • 2021-01-13 00:04

    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)

    0 讨论(0)
  • 2021-01-13 00:06

    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
    
    0 讨论(0)
提交回复
热议问题