1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのデコレーター

Posted at

はじめに

関数に特定の処理を追加させるときに使用する。

  • 関数に前処理や後処理を追加したい
  • デバック用に情報を追加したい

など、いろいろと用途がありそうなので、例としてまとめてみた。

デコレーターの使い方

デコレーターを追加したい関数の前に@デコレーター関数と宣言することで有効になる。
例えば、デバック用に関数名、引数をprintするdebug()というデコレーター使う場合は下記のようになる。例はすべての関数の前に@debugとデコレーターを宣言しているが、必要な関数だけデコレーターすればよい。

sample
def debug(func):
	def wrapper(*args, **kwargs):
		print(f'-start-\n関数:{func.__name__}\n引数:{args},{kwargs}')
		ret = func(*args, **kwargs)
		print(f'-end---')
		return ret
	return wrapper

@debug
def sample1():
	return 'hello'
print(sample1())
# -start-
# 関数:sample1
# 引数:(),{}
# -end---
# hello

@debug
def sample2(a,b):
	ret = a+b
	return ret
print(sample2(1,2))
# -start-
# 関数:sample2
# 引数:(1, 2),{}
# -end---
# 3

@debug
def sample3(list):
	ret=0
	for i in list:
		ret = ret+i
	return ret
print(sample3(list))
# -start-
# 関数:sample3
# 引数:([1, 2, 3, 4, 5, 6, 7, 8, 9, 10],),{}
# -end---
# 55

@debug
def sample4(*args):
	ret=0
	for i in args:
		ret = ret+i
	return ret
print(sample4(1,2,3,4,5,6,7,8,9,10))
# -start-
# 関数:sample4
# 引数:(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),{}
# -end---
# 55

@debug
def sample5(dict):
	ret =0
	for k,v in dict.items():
		print(k,v)
		ret = ret+v
	return ret
dict = {'':0,'':1,'':2,'':3}
print(sample5(dict))
# -start-
# 関数:sample5
# 引数:({'零': 0, '壱': 1, '弐': 2, '参': 3},),{}
# 零 0
# 壱 1
# 弐 2
# 参 3
# -end---
# 6

@debug
def sample6(**kwargs):
	ret =0
	for k,v in kwargs.items():
		print(k,v)
		ret = ret+v
	return ret
print(sample6(=0,=1,=2,=3))
# -start-
# 関数:sample6
# 引数:(),{'零': 0, '壱': 1, '弐': 2, '参': 3}
# 零 0
# 壱 1
# 弐 2
# 参 3
# -end---
# 6
	
@debug
def sample7(*args, **kwargs):
	ret =0
	for i in args:
		ret = ret+i
	for k,v in kwargs.items():
		print(k,v)
		ret = ret+v
	return ret
print(sample7(1,2,3,4,5,6,7,8,9,10,=0,=1,=2,=3))
# -start-
# 関数:sample7
# 引数:(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),{'零': 0, '壱': 1, '弐': 2, '参': 3}
# 零 0
# 壱 1
# 弐 2
# 参 3
# -end---
# 61
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?