enum - getting value of enum on string conversion

后端 未结 2 1406
渐次进展
渐次进展 2020-12-01 03:01

I have following enum defined

from enum import Enum


class D(Enum):
    x = 1
    y = 2


print(D.x)

now the printed value is

<         


        
相关标签:
2条回答
  • 2020-12-01 03:49

    You are printing the enum object. Use the .value attribute if you wanted just to print that:

    print(D.x.value)
    

    See the Programmatic access to enumeration members and their attributes section:

    If you have an enum member and need its name or value:

    >>>
    >>> member = Color.red
    >>> member.name
    'red'
    >>> member.value
    1
    

    You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

    class D(Enum):
        def __str__(self):
            return str(self.value)
    
        x = 1
        y = 2
    

    Demo:

    >>> from enum import Enum
    >>> class D(Enum):
    ...     def __str__(self):
    ...         return str(self.value)
    ...     x = 1
    ...     y = 2
    ... 
    >>> D.x
    <D.x: 1>
    >>> print(D.x)
    1
    
    0 讨论(0)
  • 2020-12-01 04:00

    I implemented access using the following

    class D(Enum):
        x = 1
        y = 2
    
        def __str__(self):
            return '%s' % self.value
    

    now I can just do

    print(D.x) to get 1 as result.

    You can also use self.name in case you wanted to print x instead of 1.

    0 讨论(0)
提交回复
热议问题