1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonデコレーターがややこしかったので覚書

Posted at

#コード

def print_more(func):
    def wrapper(*args, **kwargs):
        print('asdf')
        result = func(*args, **kwargs)
        print('result', result)
        return result
    return wrapper



def print_info(func):
    def wrapper(*args, **kwargs):
        print('start')
        result = func(*args, **kwargs)
        print('end')
        return result
    return wrapper

@print_info
@print_more
def add_num(a, b):
    return a + b

r = add_num(10, 20)
print(r)

#実行結果

start
asdf
result 30
end
30

#解説
上記の

@print_info
@print_more
def add_num(a, b):
    return a + b

r = add_num(10, 20)
print(r)

は、

f = print_info(print_more(add_num))

r = f(10, 20)


print(r)

してるのと同じ。

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?