2017年10月16日 星期一

[Python] Enum

 Python   Enum  



Introduction


Let’s see some usual samples of using enum.



Environment

Python 3.6.2



Implement


Enum
from enum import Enum

class ProductTypeEnum(Enum):
     book = 1
     clothes = 2
     toy = 3



Creating an enum

# New enum
prod_clothes = ProductTypeEnum.clothes
print(prod_clothes)

# Create enum obeject from a string(name)
prod_book1 = ProductTypeEnum['book']
print(prod_book1)

# Create enum obeject from an int(value)
prod_book2 = ProductTypeEnum(1)
print(prod_book2)


>> ProductTypeEnum.clothes
>> ProductTypeEnum.book
>> ProductTypeEnum.book


Get enum name or value

# get name or value
name = ProductTypeEnum.toy.name
value = ProductTypeEnum.toy.value
print(name)
print(value)

>> toy
>> 3

Compare

print(prod_clothes==prod_book1)
print(prod_book1==prod_book2)

>> False
>> True



IntEnum

from enum import IntEnum

class SizeEnum(IntEnum):
     small = 1
     medium = 2
     large = 3



Creating an enum

# New enum
lg = SizeEnum.large
print(lg)

# Create enum obeject from a string(name)
md1 = SizeEnum['medium']
print(md1)

# Create enum obeject from a string(name)
md2 = SizeEnum(2)
print(md2)


>> SizeEnum.large
>> SizeEnum.medium
>> SizeEnum.medium


Get enum name or value

name = SizeEnum.small.name
value = SizeEnum.small.value
print(name)
print(value)
>> small
>> 1

Compare

print(lg==3)
print(lg==5)
print(md1==md2)
>> True
>> False
>> True




Reference








沒有留言:

張貼留言