pythonの'@'記号を関数修飾子として使用


'@'記号が関数修飾子として使用するのはpython 2である.4新しく追加された機能で、修飾子は関数定義の前の行に表示され、関数定義と同じ行には許可されません.すなわち@A def():不正です.モジュールまたはクラス定義レイヤ内でのみ関数を修飾できます.クラスを修飾することはできません.
修飾子は、修飾された関数をパラメータとし、修飾された同名の関数または他の呼び出し可能なものを返す関数です.
次の例を参照してください.
    >>> def spamrun(fn):
    ... def sayspam(*args):
    ... print "spam, spam, spam"
    ... return sayspam
    ...
    >>> @spamrun
    ... def useful(a, b):
    ... print a**2 + b**2
    ...
    >>> useful(3,4)
    spam, spam, spam

python :http://www.python.org/dev/peps/pep-0318/, 。


Listing 1. Bad decorator that does not even return function
            
>>> def spamdef(fn):
... print "spam, spam, spam"
...
>>> @spamdef
... def useful(a, b):
... print a**2 + b**2
...
spam, spam, spam
>>> useful(3, 4)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: 'NoneType' object is not callable

A decorator might return a function, but one that is not meaningfully associated with the undecorated function:
Listing 2. Decorator whose function ignores passed-in function
        
>>> def spamrun(fn):
... def sayspam(*args):
... print "spam, spam, spam"
... return sayspam
...
>>> @spamrun
... def useful(a, b):
... print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam

Finally, a better behaved decorator will in some way enhance or modify the action of the undecorated function:
Listing 3. Decorator that modifies behavior of undecorated func
        
>>> def addspam(fn):
... def new(*args):
... print "spam, spam, spam"
... return fn(*args)
... return new
...
>>> @addspam
... def useful(a, b):
... print a**2 + b**2
...
>>> useful(3,4)
spam, spam, spam

25