LoginSignup
3
4

More than 5 years have passed since last update.

関数のデコレーターを作る

Last updated at Posted at 2015-04-15

以下の様に関数の前/後処理をするデコレーター (tag付き) を作って使い回したい.

>>> @MyDecorator('any-tag')
... def foo():
...     print u'foo'
... 
>>> foo():

pre-action. tag=any-tag.
foo
post-action. tag=any-tag.

この様にして作る.

class MyDecorator(object):

    def __init__(self, tag):
        self._tag = tag

    def __call__(self, f0):
        def decorated(*args, **kwargs):
            print u'pre-action. tag=' + self._tag
            ret = f0(*args, **kwargs)
            print u'post-action. tag=' + self._tag
            return ret
        return decorated

functools.wrapsを使った版.

@termoshtt さん、ありがとうございます (^◇^)

from functools import wraps

def MyDecorator(tag):
    def dec(f0):
        @wraps(f0)
        def decorated(*args, **kwargs):
            print u'pre-action. tag=' + tag
            ret = f0(*args, **kwargs)
            print u'post-action. tag=' + tag
            return ret
        return decorated
    return dec
3
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4