Is there any way to define the enum in python?

This question already has an answer here:

  • How can I represent an 'Enum' in Python? 43 answers

  • OFFLINE = 1
    ONLINE = 2
    LOGIN = 3
    

    You can wrap it in a class if you want STATUS_T.OFFLINE style of access. Python is a dynamically typed language so the concept of an enum makes little sense, all you can do is have range of meaningful values you can set something to.

    Apparently, an equivalent has been added in 3.4, see How can I represent an 'Enum' in Python?


    Not really.

    The most common idiom is to define a set of constants at the class level:

    class PhonyEnum(object):
         OFFLINE = 1
         ONLINE = 2
         LOGIN = 3
    

    It's up to you to use them as constants:

    if result == PhonyEnum.ONLINE: 
       do_something
    

    Others also do the same thing at the module level rather than the class level

    链接地址: http://www.djcxy.com/p/91746.html

    上一篇: 如何定义全局变量?

    下一篇: 有没有什么办法来定义在Python中的枚举?