如何在Python中使用按位标志

时间:2019-05-23 16:55:51

标签: python python-2.7

从枚举导入Enum

class InputTypes(Enum):
    """
    Flags to represent the different kinds of input we
    are acting on from the user
    """
    KEYBOARD = 0b00000001,
    MOUSE_BUTTONS = 0b00000010,
    MOUSE_MOVE = 0b00000100,
    ALL = 0b11111111


if __name__ == "__main__":
    x = (InputTypes.KEYBOARD | InputTypes.MOUSE_BUTTONS)

我遇到错误:

TypeError: unsupported operand type(s) for |: 'InputTypes' and 'InputTypes'

在python 2.7和python3中,如何正确定义和使用某些标志?

3 个答案:

答案 0 :(得分:1)

您可以使用IntFlag来代替基本的Enum

from enum import IntFlag
class InputTypes(IntFlag):
    # Rest of your code

答案 1 :(得分:1)

Enum基类重写类变量访问权限,以使它们返回子类本身的实例。如果您不继承Enum(并删除逗号),则代码不会崩溃。

请注意,使用InputTypes(Enum)可以使用Enum条目集代替位图来获得相同的结果

答案 2 :(得分:0)

如果需要Python 2.7 / 3解决方案,则要使用 <thead> <tr> <th>S</th> <th>Item Code</th> <th>Description</th> <th>Unit</th> <th>Unit Price</th> <th>Qty</th> <th>Amount($) </th> </tr> </thead> @foreach($product_sale_data as $key=>$product_sale_data) @if ( $key % 22 == 0 && $key ) // so here every 22 rows after this will go <thead> <tr> <th>S</th> <th>Item Code</th> <th>Description</th> <th>Unit</th> <th>Unit Price</th> <th>Qty</th> <th>Amount($) </th> </tr> </thead> @endif <tbody> @php $product_data = \App\Product::find($product_sale_data->product_id); if($product_data->sale_unit_id) ...continue your code (高级枚举)。如果数值不重要,则可以使用aenum

Flag

如果值很重要(意味着您将使用它们作为整数),请改用from aenum import Flag, auto class InputTypes(Flag): """ Flags to represent the different kinds of input we are acting on from the user """ KEYBOARD = auto() MOUSE_BUTTONS = auto() MOUSE_MOVE = auto() ALL = KEYBOARD | MOUSE_BUTTONS | MOUSE_MOVE