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 1 year has passed since last update.

【Python】「デコレータ」「ジェネレータ」「イテレータ」まぎわらしい用語を見比べてみた

Last updated at Posted at 2023-04-16

それぞれの意味を整理してみる

デコレータ

すでに存在する関数に対して、処理の追加や変更を行うための機能
Python には以下のデコレータが標準で用意されている

  • @classmethod ・・・ クラスメソッド(インスタンス化しなくても直接呼び出せるメソッド)を定義
  • @staticmethod ・・・ 静的メソッド(クラスメソッドと同じくインスタンス化せずに呼び出し可能)を定義
  • @property ・・・ 変更できないプロパティを定義

ジェネレータ

リストやタプルと同じ機能を持つオブジェクトを生成することができる機能
リストやタプルと同じように for で取り出すことが可能

イテレータ

要素を1つずつ取り出せるオブジェクト
リストにできなくて、イテレータオブジェクトにできる機能は、次の要素を尋ねること

それぞれの基本形を見比べる

デコレータ

'Before the...' と 'After the...' の間に、'Hello!' を表示されるように、 @my_decorator の部分で デコレート(修飾)しています。

def my_decorator(func):
  def wapper():
    print("Before the function is called.")
    func()
    print("After the function is called.")
  return wapper

@my_decorator
def say_hello():
  print("Hello!")
  
... say_hello()
...
Before the function is called.
Hello!
After the function is called.

ジェネレータ

yield で1つずつ要素を作っています。
変数 items に格納し、for文で繰り返し取り出しています。

def generator_items():
    yield 'a'
    yield 'b'
    yield 'c'

items = generator_items()
for item in items:
...    print(item)
...
a
b
c

イテレータ

iter() で直前に作ったリストと同じ要素が入っているイテレータオブジェクトを生成しています。
next() で次の要素を尋ねています。次の要素が無くなったので、最後に 'StopIteration' と返ってきています。

list = ['a', 'b', 'c']
items = iter(list):
for item in items:
...    print(next(item))
...
a
b
c
StopIteration
1
2
1

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?