getting object name and function name

前端 未结 2 1004
被撕碎了的回忆
被撕碎了的回忆 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: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
    

提交回复
热议问题