Enum in Python

Asked 2 years ago, Updated 2 years ago, 46 views

I usually use C, and I'm going to learn Python. Is the same function as the enum of c supported in Python?

python python3

2022-09-21 19:05

1 Answers

The enum function was added in Python version 3.4. Pypi also provides enum functionality in older versions (3.3, 3.2, 3.1, 2.7, 2.6, 2.5, 2.4). If you want to use enum in the old version, $pip install enum Not that $pip install enum34 If you do not have a number, it is not compatible.)

Here's how to use it: If you are going to use it similar to C

from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')

Or write it like this

class Animals(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4

In older versions

def enum(**enums):
    return type('Enum', (), enums)

Animal = enum(ant=1, bee=2, cat=3, dog=4)
print Animal.ant

I wrote it with that.

If you want to number it automatically, here's how to write it:

def enum(*sequential, **named):
    enums = dict(zip(sequential, range(len(sequential))), **named)
    return type('Enum', (), enums)

Animal = enum('ant', 'bee', 'cat', 'dog')
print Animal.ant


2022-09-21 19:05

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.