パープルハット

※当サイトではGoogleアドセンス広告を利用しています

Python 列挙型Enumの使い方



宣言

from enum import Enum

class PType(Enum):
        normal = 0
        fighting = 1
        flying = 2
        poison = 3





表示

from ptype import PType

#表示
print(PType.normal)
print(f"name : {PType.normal.name}")
print(f"value : {PType.normal.value}")


実行結果

PType.normal
name : normal
value : 0





nameから取得

from ptype import PType

#表示
normal = PType['normal']
poison = PType['poison']
print(f"PType['normal'] : {normal}")
print(f"PType['poison']: {poison}")


実行結果

PType['normal'] : PType.normal
PType['poison']: PType.poison





valueから取得

from ptype import PType

#表示
type0 = PType(0)
type2 = PType(2)
print(f"PType(0) : {type0}")
print(f"PType(2) : {type2}")


実行結果

PType(0) : PType.normal
PType(2) : PType.flying





for文でループ

from ptype import PType

for ptype in PType:
    print(f"{ptype}")


実行結果

PType.normal
PType.fighting
PType.flying
PType.poison