Skip to content

Instantly share code, notes, and snippets.

@ged1959
Created June 30, 2017 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ged1959/2a3a04b921ca565a58a221c5b7811d35 to your computer and use it in GitHub Desktop.
Save ged1959/2a3a04b921ca565a58a221c5b7811d35 to your computer and use it in GitHub Desktop.
pythonのdecorator、elvの勉強会で。

Webアプリについて学ぼうシリーズ、其の参

created: 2017/0629;

リスト内包表示については、例えば、以下を参照。

デコレータの事例

先生が紹介していた以下のコードは、分かりやすいぞ。

def dec(func):
    def _dec():
        print('decorator!')
        func()
    return _dec

@dec
def function():
    print('function!')

function()

これは、@マークを使わなくても、以下のように書ける。

def dec(func):
    def _dec():
        print('decorator!')
        func()
    return _dec

def function():
    print('function!')

f = dec(function)
f()

さらに、蛇足ぽいけど、以下も。

def dec(func):
    def _dec():
        print('decorator!')
        func()
    return _dec

def function():
    print('function!')

dec(function)()

引数を取る事例。引数を表示する関数を、偶数ならerrorと表示。

def check(function):
    def dec(x):
        if x % 2 == 0:
            print('error')
        else:
            print(x)
    return dec

@check
def func(x):
    print(x)

func(9)
func(8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment