V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2016-04-10 16:03:52 +08:00 · 3126 次点击
    这是一个创建于 2944 天前的主题,其中的信息可能已经有所发展或是发生改变。
    >>> 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 条回复    2016-04-11 08:58:19 +08:00
    sleshep
        1
    sleshep  
       2016-04-10 16:10:30 +08:00
    貌似有个__repr__属性
    xiongbiao
        2
    xiongbiao  
       2016-04-10 16:28:50 +08:00   ❤️ 1
    Color.red.value
    tetsuo
        3
    tetsuo  
    OP
       2016-04-10 16:46:10 +08:00
    那 Color.red 到底是实例还是属性啊,还有枚举类和普通的类有什么区别,作用是什么??求大神解答
    bp0
        4
    bp0  
       2016-04-10 16:47:01 +08:00
    建议看看单例模式
    zonghua
        5
    zonghua  
       2016-04-10 16:57:22 +08:00
    @tetsuo 类,类里面的变量是类自己实例化的自己。
    xuyuxi
        6
    xuyuxi  
       2016-04-10 17:14:56 +08:00
    Color().red
    congeec
        7
    congeec  
       2016-04-10 17:23:08 +08:00
    @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  
       2016-04-10 17:53:25 +08:00 via Android
    看了下代码,用的 metaclass 。

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

    简单地说,所有的 member 都被替换过了。
    qnnnnez
        9
    qnnnnez  
       2016-04-10 17:55:12 +08:00 via Android
    Drifter
        10
    Drifter  
       2016-04-10 20:42:45 +08:00
    ryanking8215
        11
    ryanking8215  
       2016-04-11 08:58:19 +08:00
    class Color(enum.IntEnum)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2235 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 09:33 · PVG 17:33 · LAX 02:33 · JFK 05:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.