trsqxyz / tips

Tips are here.
The Unlicense
0 stars 0 forks source link

デコレータ #3

Open trsqxyz opened 10 years ago

trsqxyz commented 10 years ago

現状での理解(動作の順序)

  1. デコレータにはデコレートされた関数が渡される
  2. デコレータでネストされている関数にデコレートされた関数とインスタンスが渡る
  3. 関数を戻す

    ex.

https://github.com/trsqxyz/bingo/blob/master/bingo.py

trsqxyz commented 10 years ago

デコレートされたじゃなくてラップされたっぽい

trsqxyz commented 10 years ago
  1. デコレータにラップした関数が渡される
  2. デコレータに書いてある関数がラップした関数として振る舞う
  3. デコレータされたラップした関数が実行される このときfunc動作させる
  4. デコレータに関数戻す
def decorator(func):  #  ラップした関数が渡される
    def inner(arg):  #  ラップした関数として振る舞う 引数をラップした関数と一致させる
        print "decorator!" * arg
        func(arg)  #  ラップした関数の処理が実行される
    return inner  #  デコレータに戻す

@decorator
def spam(arg):
    print "spam" * arg

spam(5)

# -> decorator!decorator!decorator!decorator!decorator!
# -> spamspamspamspamspam
trsqxyz commented 10 years ago

デコレータに関数が渡されるっていうのがムズい ラップした関数と引数の関係がムズい 関数を戻すのがムズい

trsqxyz commented 10 years ago

クラスに self が渡されるみたいな感じで function が渡されるのかな