python枚举的用法示例

 示例1:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from enum import Enum


class CheckResult(Enum):
    success_running = 'hehe'
    success_non_running = 'haha'
    error_ping_ = 'ping 错了'
    error_ssh = 'ssh 不行'
    error_few = '启动一点'
    error_all_failure = '失败了'
    error_unexpected = '意外了老铁'


print CheckResult.success_running.name         # success_running
print CheckResult.success_running.value        # hehe
print CheckResult.error_unexpected_running.value   # 意外了老铁

示例二:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from enum import Enum, unique


# 继承枚举类,unique确保唯一的枚举值
@unique
class MissionEnum(Enum):
    """卫星代码"""
    BC1 = '66'
    BC2 = '77'
    BC3 = '88'

    @classmethod
    def dict_k_v(cls):
        return {m.name: m.value for m in cls}

    @classmethod
    def dict_v_k(cls):
        return {m.value: m.name for m in cls}


if __name__ == '__main__':
    print(MissionEnum.dict_k_v())               # {'BC1': '66', 'BC2': '77', 'BC3': '88'}
    print(MissionEnum.dict_v_k())               # {'77': 'BC2', '88': 'BC3', '66': 'BC1'}
    print(MissionEnum.dict_k_v().get('BC1'))    # 66

听歌一句劝,不要做运维

你可能感兴趣的:(python,python,前端,服务器)