推荐学习书目
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 · 3947 views
    This topic created in 3699 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
        1
    sleshep  
       Apr 10, 2016
    貌似有个__repr__属性
    xiongbiao
        2
    xiongbiao  
       Apr 10, 2016   ❤️ 1
    Color.red.value
    tetsuo
        3
    tetsuo  
    OP
       Apr 10, 2016
    那 Color.red 到底是实例还是属性啊,还有枚举类和普通的类有什么区别,作用是什么??求大神解答
    bp0
        4
    bp0  
       Apr 10, 2016
    建议看看单例模式
    zonghua
        5
    zonghua  
       Apr 10, 2016
    @tetsuo 类,类里面的变量是类自己实例化的自己。
    xuyuxi
        6
    xuyuxi  
       Apr 10, 2016
    Color().red
    congeec
        7
    congeec  
       Apr 10, 2016
    @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
        8
    qnnnnez  
       Apr 10, 2016 via Android
    看了下代码,用的 metaclass 。

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

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