のんびりしているエンジニアの日記

ソフトウェアなどのエンジニア的な何かを書きます。

Pythonのデコレータ

Sponsored Links

皆さんこんにちは
お元気ですか?私はお酒をのむぞおおおおお

さて、デコレータと呼ばれるPythonの機能について
お話したいと思います。

デコレータとは?

関数を修飾してくれるPython独特の機能ですね
もうこれ、例ないと意味不明でしょう。
因みに@helloがデコレータであり、関数を修飾する。

def hello(func):
	func()
	print "Hello World"

@hello
def goodbye():
	print "goodbye world"

if __name__ == '__main__':
	goodbye

出力は以下の通り

goodbye world
Hello World

因みに普通に書くとこうなります。

def hello(func):
	func()
	print "Hello World"

def goodbye():
	print "goodbye world"

if __name__ == '__main__':
	hello(goodbye)

修飾された関数を呼び出すと、元の関数の引数に関数オブジェクトを入れることができます。
まぁスマートに記述ができるということですね。(よくこんな手法思いついたな)

引数有りのデコレータ

デコレータ有り

def function(result):
	def recieve_func(func):
		def printOut():
			print "------"
			func()
			print result
			print "------"
		return printOut
	return recieve_func

@function("goodbye")
def example():
	print "hello world"

example()

デコレータなし

def function(result):
	def recieve_func(func):
		def printOut():
			print "------"
			func()
			print result
			print "------"
		return printOut
	return recieve_func

def example():
	print "hello world"

func = function("goodbye")(example)
func()

デコレータのネスト

デコレータ有り

def hello(func):
	def printOut():
		print "Hello World"
		func()
	return printOut

def morning(func):
	def printOut():
		print "hello good world"
		func()
	return printOut

@hello
@morning
def goodbye():
	print "goodbye world"

if __name__ == '__main__':
	goodbye()

デコレータ無し

def hello(func):
	def printOut():
		print "Hello World"
		func()
	return printOut

def morning(func):
	def printOut():
		print "hello good world"
		func()
	return printOut

def goodbye():
	print "goodbye world"

if __name__ == '__main__':
	hello(morning(goodbye))()

感想

これらから、元の関数をいじらず現在の関数に対し、新しい機能を追加することができる。
これ、使いこなすのは難しそう…。