1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python デコレータについて

Posted at

デコレートとは

入力として関数を一つ取り、別の関数を返す関数。
関数の前後で何かしたいときに使用する。

使用例

# デコレータ
def test(func):
    def new_func(*args, **kwargs):
        print("start")
        result = func(*args, **kwargs)
        print("end")
        return result
    return new_func

# デコレータ対象
# アノテーションをつけることにより、デコレートされる
@test
def greeting():
    print("Hello")


greeting()
結果
start
Hello
end
#  デコレータについて
# dumpが呼び出されてfunc=doubleとして実行
def dump(func):
    "入力引数と出力値を表示する"
    def wrapped(*args, **kwards):
        print("Fuction name: %s" % func.__name__)
        print("Input arguments: %s " % ' '.join(map(str, args)))
        print("Input keyaeorods: %s " % kwards.items())
        output = func(*args, **kwards)
        print("Output:", output)
    return wrapped

@dump
def double(*args, **kwards):
    "Double every arguments"
    output_list = [2 * args for arg in args]
    output_dict = {k: 2 * v for k, v in kwards.items()}
    return output_list, output_dict
結果
Fuction name: double
Input arguments: 3 5
Input keyaeorods: dict_items([('first', 100), ('next', 98.6), ('last', 40)])
Output: ([(3, 5, 3, 5), (3, 5, 3, 5)], {'first': 200, 'next': 197.2, 'last': 80})

参考文献

「入門 Python3」(著:Bill Lubanovic)

1
2
0

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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?