简体   繁体   English

布尔变量的 Python 枚举

[英]Python Enum for Boolean variable

I'm using class enum.Enum in order to create a variable with selected members.我正在使用类 enum.Enum 来创建具有选定成员的变量。

The main reason is to enable other developers in my team to use the same convention by selecting one of several permitted members for variable.主要原因是通过为变量选择几个允许的成员之一,使我团队中的其他开发人员能够使用相同的约定。

I would like to create a Boolean variable in the same way, enabling other developers to select either True or False.我想以同样的方式创建一个布尔变量,让其他开发人员可以选择 True 或 False。

Is it possible to define an enum which will receive True False options?是否可以定义一个将接收 True False 选项的枚举? Is there any better alternative?有没有更好的选择?

The following options don't work:以下选项不起作用:

boolean_enum = Enum('boolean_enum', 'True False') boolean_enum = Enum('boolean_enum', '真假')

boolean_enum = Enum('boolean_enum', True False) boolean_enum = Enum('boolean_enum', True False)

boolean_enum = Enum('boolean_enum', [('True', True), ('False', False)])

Checkout the documentation of this API: https://docs.python.org/3/library/enum.html#functional-api查看此 API 的文档: https : //docs.python.org/3/library/enum.html#functional-api

If you just specify 'True False' for the names parameter, they will be assigned automatic enumerated values (1,2) which is not what you want.如果您只是为名称参数指定 'True False',它们将被分配自动枚举值 (1,2),这不是您想要的。 And of courase you can't just send True False without it being a string argument for the names parameter.当然,你不能只发送 True False 而不是 names 参数的字符串参数。

so what you want is one of the options that allow you to specify name and value, such as the above.所以你想要的是允许你指定名称和值的选项之一,例如上面的。

Edit:编辑:
When defined as above, the enum elements aren't accessible by boolean_enum.True (but they are accessible by boolean_enum['True'] or boolean_enum(True) ).当如上定义时,枚举元素不能被boolean_enum.True访问(但它们可以被boolean_enum['True']boolean_enum(True) )。
To avoid this issue, the field names can be changed and defined as为避免此问题,可以更改字段名称并将其定义为

Enum('boolean_enum', [('TRUE', True), ('FALSE', False)])

Then accessed as boolean_enum.TRUE or boolean_enum['TRUE'] or boolean_enum(True)然后作为boolean_enum.TRUEboolean_enum['TRUE']boolean_enum(True)

Nowadays (python 3.6+) this could be much more conveniently achieved by using enum.Flag :如今(python 3.6+)这可以通过使用enum.Flag更方便地实现:

from enum import Flag

class Boolean(Flag):
    TRUE = True
    FALSE = False

An added benefit of enum.Flag over enum.Enum is that it supports (and is closed under) bit-wise operators ( &,|,~ ) from the get-go: enum.Flag对于enum.Enum一个额外好处是它从一开始就支持(并在其下关闭)按位运算符( &,|,~ ):

>>> Boolean.TRUE & Boolean.FALSE
Boolean.FALSE
>>> Boolean.TRUE | Boolean.FALSE
Boolean.TRUE
>>> ~Boolean.FALSE
Boolean.TRUE

For more information see https://docs.python.org/3/library/enum.html#enum.Flag有关更多信息,请参阅https://docs.python.org/3/library/enum.html#enum.Flag

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM