【问题标题】:Python function decorator should print full method namePython 函数装饰器应该打印完整的方法名称
【发布时间】:2017-03-17 02:56:52
【问题描述】:

以下有用的装饰器测量函数的执行时间。它还打印函数的名称。但是,如果函数是方法,它还可以打印类名,那就太好了。什么是获取完整方法名称的简洁方法,例如 Class.method

import time

def timeit(f):

    def timed(*args, **kw):

        ts = time.time()
        result = f(*args, **kw)
        te = time.time()

        print('func:%r args:[%r, %r] took: %2.4f sec' % (f.__name__, args, kw, te-ts))
        return result

    return timed

【问题讨论】:

    标签: python python-3.x decorator introspection


    【解决方案1】:

    可能有更好的方法,但在 Python 2(没有__qualname__)中你可以使用

    m.im_class.__name__
    

    >>> class MyClass(object):
    ...   def foo(self):
    ...      pass
    ... 
    >>> m = MyClass.foo
    >>> print m.im_class.__name__ + '.' + m.__name__
    MyClass.foo
    

    【讨论】:

      【解决方案2】:

      .__qualname__ 呢?

      In [1]: class MyClass(object):
         ...:     def my_method(self):
         ...:         pass
         ...:
      
      In [2]: MyClass.my_method.__qualname__
      Out[2]: 'MyClass.my_method'
      

      【讨论】:

      猜你喜欢
      • 2021-05-31
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多