简体   繁体   中英

enums from c# to python (2.7)

I have code which was written in C# now i need to port it to PYTHON. The C# code has enums which cannot be implemented directly in python

Is there any work around to implement enum in python and creating instance of it, as shown in the c# code below SerialProcessState serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;

Can anyone help me in implementing this stuff in python ?

enum SerialProcessState
    {
        SERIAL_PROCESS_SEARCH_START,
        SERIAL_PROCESS_VERIFY_ELEMENTS,
        SERIAL_PROCESS_DATA,
        SERIAL_PROCESS_SEARCH_END}

    ;
SerialProcessState serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;

enum SerialProcessValue
    {
        SERIAL_PACKET_START = 0xF0,
        SERIAL_PACKET_END = 0xF1,
        SERIAL_PACKET_ESCAPE = 0xF2,
        SERIAL_PACKET_ESCAPE_START = 0x00,
        SERIAL_PACKET_ESCAPE_END = 0x01,
        SERIAL_PACKET_ESCAPE_ESCAPE = 0x02,
        SERIAL_PACKET_ELEMENTS = 0x06}

    ;

private void SerialProcess(byte serialData)
    {
        UInt16 Dummy;

        for (Dummy = 0; Dummy < 63; Dummy++) {
            serialhistory[Dummy] = serialhistory[Dummy + 1];
        }
        serialhistory[63] = serialData;

        if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) {
            serialProcessState = SerialProcessState.SERIAL_PROCESS_SEARCH_START;
            serialEscaped = false;
        }

        switch (serialProcessState) {
            case SerialProcessState.SERIAL_PROCESS_SEARCH_START:
                if ((SerialProcessValue)serialData == SerialProcessValue.SERIAL_PACKET_START) {
                    checksum = 0;
                    serialProcessState = SerialProcessState.SERIAL_PROCESS_VERIFY_ELEMENTS;
                }
                break;
  .
  .

}

Using the backported Enum *:

from enum import Enum, IntEnum

class SerialProcessState(Enum):
    search_start = 1
    verify_elements = 2
    data = 3
    search_end = 4

class SerialProcessValue(IntEnum):
    packet_start = 0xF0
    packet_end = 0xF1
    ...

You can then access them as SerialProcessValue.packet_start or SerialProcessState.search_end .

* The package name for the backport is enum34 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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