keisukeのブログ

***乱雑です!自分用のメモです!*** 統計や機械学習の勉強と、読み物を書く練習と、備忘録用のブログ

decorator

http://www.jeffknupp.com/blog/2013/11/29/improve-your-python-decorators-explained/

@currency
def price_with_tax(price, tax_rate_percentage):
    return price * (1 + tax_rate_percentage)

では、currencyがdecorator.
currencyは

def currency(f):
    def wrapper(*args, **kwargs):
        return '$' + str(f(*args, **kwargs))

    return wrapper

のように定義される。
decoratorとは、関数を返す関数。
デコレート*された*関数、この場合price_with_taxは、decoratorの引数fに代入されるように振る舞う。
price_with_taxをcurrencyでデコレーションすることによって、

price_with_tax = currency(price_with_tax)

のように代入されるイメージ。

currencyは関数を返す関数なので、price_with_taxは代入された後も関数のまま。
ただし、その機能はcurrencyによって上書きされている。