Enum is a class

so

Basic class operations can be used

That is, we can add our own methods

class Mood(Enum):
    FUNKY = 1
    HAPPY = 3

    def describe(self):
        # self is the member here
        return self.name, self.value

    def __str__(self):
        return 'my custom str! {0}'.format(self.value)

    @classmethod
    def favorite_mood(cls):
        # cls here is the enumeration
        return cls.HAPPY
>>> Mood.favorite_mood()
<Mood.HAPPY: 3>
>>> Mood.HAPPY.describe()
('HAPPY', 3)
>>> str(Mood.FUNKY)
'my custom str! 1'
Each class member of Enum is automatically converted into an instance of the current class
from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
>>> type(Color.RED)
<enum 'Color'>
>>> isinstance(Color.GREEN, Color)
True

This means that we cannot use enum members directly as their values:

>>> Color.RED == 1
False
>>> Color.RED.value == 1
False

Enumeration members also have a name attribute, which is the same as its variable name

>>> Color.RED.name == "RED"
True

The enumeration class has a big pit: when the parent class has members, the subclass cannot be defined

So, for the above Color class, if you want to define a subclass, you will get an error:

>>> class MoreColor(Color):
...     PINK = 17
...
Traceback (most recent call last):
...
TypeError: MoreColor: cannot extend enumeration 'Color'

But the parent class does not have enumeration members, it is OK to only define functions:

class Foo(Enum):
    def some_behavior(self):
        pass

class Bar(Foo):
    HAPPY = 1
    SAD = 2

This obviously greatly limits the expansion of enumeration classes, and a function that cannot access members is not very useful.


songofhawk
303 声望24 粉丝