matobaの備忘録

育児しながら働くあるエンジニアの記録

デコレータを再勉強した時のメモ

デコレータを勉強していて、なるほどがあったのでメモ。

例えば、こういうのがあったとき。

def test_decorator(func):
    print('start decorator')
    func()
    print('end decorator')

def test_method():
    print('test method')


test_decorator(test_method)

デコレータを使うと、以下のようにかける。

def test_decorator(func):
    print('start decorator')
    func()
    print('end decorator')

@test_decorator
def test_method():
    print('test method')

test_method

@ がやってるのは、修飾されたメソッドをデコレータメソッドに渡すだけ。別にcallableなメソッドを返さなくても良い。

よくある前後処理は、こういうこと。

def test_decorator(func):
    def decorated_method(*args, **kwargs):
        print('start decorator')
        result =  func(*args, **kwargs)
        print('end decorator')
        return result
    return decorated_method

@test_decorator
def test_method():
    print('test method')

test_method()

decorated_method みたいなデコレート済みのcallableなメソッドを返しているだけ。

エキスパートPythonプログラミング改訂2版に、もう少し詳しく書いてる。

エキスパートPythonプログラミング改訂2版

エキスパートPythonプログラミング改訂2版