问题
As the documentation says, an enumeration is a set of symbolic names (members) bound to unique, constant values. The PEP8 says that constants are usually named as UPPER_CASE
, should I use this notation in Python 3.4 enums? If yes, why the examples in the docs are using lower_case
?
回答1:
Update
The BDFL (Benevolent Dictator For Life) has spoken, and the Enum documentation has changed to reflect all upper-case member names.
The examples in the [previous] docs are lower-case primarily because one of the preexisting modules that Enum was based on used lower-case (or at least its author did ;).
My usage of enum has usually been something along the lines of:
class SomeEnum(Enum):
... = 1
... = 2
... = 3
globals().update(SomeEnum.__members__)
which effectively puts all the members in the module namespace.
So I would say whichever style feels more comfortable to you -- but pick a style and be consistent.
回答2:
I think they're not UPPER_CASE because, well, it just looks weird when it is. Since you can only access the enumerations through the class (e.g. my_enum.VALUE
) it looks weird if the members are capitalized. In C the members of the enumeration go into the module namespace, so it doesn't look weird (to me) when the members are capitalized, in usage:
typedef enum {OFF, ON} lightswitch;
lightswitch bathroomLight = ON;
But in Python you access them through the enumeration class that you create, and it looks weird to go from ClassStyle names to ALL_CAPS.
class Lightswitch(Enum):
OFF = 0
ON = 1
# isn't that weird?
my_light = Lightswitch.OFF
Bottom line, I think it's just aesthetic. I've been wrong before, though, and I realize that this is just my opinion.
回答3:
When in doubt about style, I usually defer to the style used in standard library code and examples from the official documentation. It keeps me from wasting time on arbitrary decisions.
So in this case, I recommend lower case, like variable names.
来源:https://stackoverflow.com/questions/21359130/should-3-4-enums-use-upper-case-with-underscores