delhi09の勉強日記

技術トピック専用のブログです。自分用のメモ書きの投稿が多いです。あくまで「勉強日記」なので記事の内容は鵜呑みにしないでください。

PythonでEnumをstaticメソッド内でループする

やりたいことはタイトルの通り。

以下の3つの書き方があった。
②が一番スマートだが、Enumの仕様上こういう書き方もできるんだって知っておいて損はないと思った。

※ この例では都道府県コードから都道府県を引くstaticメソッドを実装している。

書き方①

Enumはクラスをループすると各メンバーを取得できるので、以下のようにかける。

from enum import Enum

class Pref(Enum):
    SAITAMA = (11, "埼玉県", 7330000)
    CHIBA = (12, "千葉県", 6270000)
    TOKYO = (13, "東京都", 13960000)
    KANAGAWA = (14, "神奈川県", 9050000)

    def __init__(self, pref_code: int, pref_name: str, population: int):
        self.pref_code = pref_code
        self.pref_name = pref_name
        self.population = population

    @staticmethod
    def get_pref(pref_code: int):
        for pref in Pref:
            if pref.pref_code == pref_code:
                return pref

print(Pref.get_pref(14).pref_name) # 神奈川県

書き方②

「書き方①」で書けるなら、classmethodを使って以下のようにも書ける。

from enum import Enum

class Pref(Enum):
    SAITAMA = (11, "埼玉県", 7330000)
    CHIBA = (12, "千葉県", 6270000)
    TOKYO = (13, "東京都", 13960000)
    KANAGAWA = (14, "神奈川県", 9050000)

    def __init__(self, pref_code: int, pref_name: str, population: int):
        self.pref_code = pref_code
        self.pref_name = pref_name
        self.population = population

    @classmethod
    def get_pref(cls, pref_code: int):
        for pref in cls:
            if pref.pref_code == pref_code:
                return pref

print(Pref.get_pref(12).pref_name) # 千葉県

書き方③

Enum__members__というフィールドにname-valueの辞書を保持しているので、以下のようにも書ける。

from enum import Enum

class Pref(Enum):
    SAITAMA = (11, "埼玉県", 7330000)
    CHIBA = (12, "千葉県", 6270000)
    TOKYO = (13, "東京都", 13960000)
    KANAGAWA = (14, "神奈川県", 9050000)

    def __init__(self, pref_code: int, pref_name: str, population: int):
        self.pref_code = pref_code
        self.pref_name = pref_name
        self.population = population

    @classmethod
    def get_pref(cls, pref_code: int):
        for pref in cls.__members__.values():
            if pref.pref_code == pref_code:
                return pref

print(Pref.get_pref(13).pref_name) # 東京都