Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's enum equivalent [duplicate]

Tags:

Possible Duplicate:
What’s the best way to implement an ‘enum’ in Python?

What is the Python idiom for a list of differently indexed names (like Enum in C/C++ or Java)?

Clarification: I want a property of a value to be set to a restricted range, such as card suites Heart, Club, Spade, Diamond. I could represent it with an int in range 0..3, but it would allow out of range input (like 15).

like image 488
Amir Rachum Avatar asked Jul 14 '10 17:07

Amir Rachum


People also ask

What is equivalent of enum in Python?

The enums are evaluatable string representation of an object also called repr(). The name of the enum is displayed using 'name' keyword. Using type() we can check the enum types.

Can enum have duplicate values?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can enums have the same value python?

By definition, the enumeration member values are unique. However, you can create different member names with the same values.

Do enums have to be unique?

Enum names are in global scope, they need to be unique.


2 Answers

class Suite(object): pass  class Heart(Suite): pass class Club(Suite): pass 

etc.

A class in python is an object. So you can write

x=Heart 

etc.

like image 98
snakile Avatar answered Oct 07 '22 22:10

snakile


here is very same popular question on stackoverflow

Edit:

class Suite(set):     def __getattr__(self, name):         if name in self:             return name         raise AttributeError  s1 = Suite(['Heart', 'Club', 'Spade', 'Diamond']) s1.Heart 
like image 40
shahjapan Avatar answered Oct 07 '22 22:10

shahjapan