LoginSignup
1
0

More than 3 years have passed since last update.

python Bottleの基本5 独自のデコレーター

Posted at

デコレータは、関数の変更をせずに機能を追加する機能を言います。
例えば関数Test()は

test.py
def Test():
    return "Hello World"

これは、"Hello World"の文字列を返す関数です。

H1_deco.py
def H1(f):
    def f0(*a,**b):
        return "<h1>%s</h1>"%f(*a,**b)
    return f0
@H1
def Test():
    return "Hello World"
print(Test())

H1関数は、h1タグを追加するデコレート関数です。
実行すると

<h1>Hello World</h1>

を返します。

下記は、デコレータにパラメータを渡す例です。

tag0.py
def tag(t):
    def f0(f):
        def f1(*a,**b):
            return "<%s>%s</%s>"%(t,f(*a,**b),t)
        return f1
    return f0
@tag('div')
def test():
    return "Hello World"
print(test())

この例は、tag関数にタグ名を渡す例です。
実行結果は、下記の通りです。

<div>Hello World</div>
tag1.py
def tag(t):
    def f0(f):
        def f1(*a,**b):
            return "<%s>%s</%s>"%(t,f(*a,**b),t)
        return f1
    return f0

@tag('div')
@tag('h1')
def test():
    return "Hello World"

print(test())

デコレータを2重にした例です。

<div><h1>Hello World</h1></div>
1
0
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
0