25

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).

Community
  • 1
  • 1
Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • 1
    http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python – James Jul 14 '10 at 17:42
  • Similar question: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python – Jordan Jul 14 '10 at 17:42

2 Answers2

16
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.

snakile
  • 52,936
  • 62
  • 169
  • 241
8

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
Community
  • 1
  • 1
shahjapan
  • 13,637
  • 22
  • 74
  • 104