0
0

More than 1 year has passed since last update.

【Python】enumとは

Posted at

enumとは

enumは、列挙型と呼ばれる複数の定数を1クラスにまとめて保持できるもの。

定義方法

enumは、標準ライブラリのenumモジュールEnumクラスを継承させることで使用できる。
定義方法のサンプルが以下となる。

from enum import Enum

class Color(Enum):
    #<name> = <value>
    RED = 0
    GREEN = 1
    BULE = 2

変数名がname、値がvalueとなる。enumでは、同じ名前のメンバを複数持つことができないため、下記のように定義するとエラーになる。

class Color(Enum):
    # <name> = <value>
    RED = 0
    RED = 1   
# TypeError: Attempted to reuse key: 'RED'

一方、同じvalueを持つメンバは複数持つことができる。もし、重複を避けたい場合は@uniqueを使うことで重複時エラーが発生する。

値の使い方

列挙型における値の扱い方は以下のようになる。
また、enumはfor文を使って値を取得することができる。

# 値の取得
print(Color.RED)        # Color.RED
print(Color.RED.name)   # RED
print(Color.RED.value)  # 0
print(Color(0))         # Color.RED

# for文の場合
for in Color:
    print(i) 

# Color.RED
# Color.GREEN
# Color.BULE
0
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
0
0