推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
tetsuo
V2EX  ›  Python

关于 python 枚举类的一点疑问求大神解答??

  •  
  •   tetsuo · Apr 10, 2016 · 4350 views
    This topic created in 3860 days ago, the information mentioned may be changed or developed.
    >>> from enum import Enum
    >>> class Color(Enum):
    ... red = 1
    ... green = 2
    ... blue = 3
    ...
    >>> print(Color.red)
    Color.red

    执行 print ( Color.red )为什么结果是 Color.red 而不是 1 ,还有 Enum 的所有实例都是单例,这个单例是什么意思?
    修改
    11 replies  •  2016-04-11 08:58:19 +08:00
    sleshep
    sleshep
    Apr 10, 2016
    1
    貌似有个__repr__属性
    xiongbiao
    xiongbiao
    Apr 10, 2016❤️1
    2
    Color.red.value
    tetsuo
    tetsuo
    OP
    Apr 10, 2016
    3
    那 Color.red 到底是实例还是属性啊,还有枚举类和普通的类有什么区别,作用是什么??求大神解答
    bp0
    bp0
    Apr 10, 2016
    4
    建议看看单例模式
    zonghua
    zonghua
    Apr 10, 2016
    5
    @tetsuo 类,类里面的变量是类自己实例化的自己。
    xuyuxi
    xuyuxi
    Apr 10, 2016
    6
    Color().red
    congeec
    congeec
    Apr 10, 2016
    7
    @tetsuo
    一楼说的对

    ```
    >>> str(Color.red)
    'Color.red'

    >>> repr(Color.red)
    '<Color.red: 1>'
    ```

    https://docs.python.org/3/library/enum.html?highlight=enum#allowed-members-and-attributes-of-enumerations
    为嘛不看文档?
    qnnnnez
    qnnnnez
    Apr 10, 2016 via Android
    8
    看了下代码,用的 metaclass 。

    https://hg.python.org/cpython/file/3.5/Lib/enum.py#l82

    简单地说,所有的 member 都被替换过了。
    ryanking8215
    ryanking8215
    Apr 11, 2016
    11
    class Color(enum.IntEnum)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1554 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 23:32 · PVG 07:32 · LAX 15:32 · JFK 18:32
    ♥ Do have faith in what you're doing.