import time
class Timeit(object):
def __init__(self, func):
self._wrapped = func
def __call__(self, *args, **kws):
start_time = time.time()
result = self._wrapped(*args, **kws)
print("elapsed time is %s " % (time.time() - start_time))
return result
このようなクラスデコレータを作成しますが、インスタンスメソッドに使用すると動作しません。pythonクラスデコレータが動作しません
class A(object):
@Timeit
def func(self):
time.sleep(1)
return 'invoking method func'
if __name__ == '__main__':
a = A()
a.func() # Boom!
私は誰に説明できますか?通常の方法でうまく動作します。
デコレータとして使用されているだけのクラスのクラスデコレータ、ないことを。 –
これをチェックしてください。 http://stackoverflow.com/questions/9416947/python-class-based-decorator-with-parameters-that-can-decorate-a-method-or-a-fun – Prajwal
自分でデコレータを作成してみてください。関数またはインスタンスメソッドの両方で正しく動作するように、すべての面倒な作業を行うパッケージを使用し、正しく実行します。ラップを見てみましょう。 http://wrapt.readthedocs.io –