General Concept
Enumerations (enums) are used to represent a set of named values. They make code more readable and can reduce errors by replacing magic numbers or strings with named constants.
Pseudo-code:
enum Colors {
RED,
GREEN,
BLUE
}
if (currentColor == Colors.RED) {
// Do something
}
Python’s enum.Enum
Features
- Flexible Values: Enum members in Python can be associated with not just integers but also strings, tuples, or other constant values.
- Type-Safe Comparisons: Enums in Python are more type-safe, avoiding many pitfalls present in other languages.
- Iterability: Enumerations in Python are iterable, allowing easy traversal of all enum members.
- Methods and Attributes: Python enums can have methods and other attributes.
Applications & Examples
- Basic Enumeration:
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 - Flexible Values:
class Mood(Enum): HAPPY = "smiling" SAD = "crying" - Auto Value Assignment:
from enum import auto class Color(Enum): RED = auto() GREEN = auto() BLUE = auto() - Iterating:
for color in Color: print(color.name, color.value) - Methods within Enums:
class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 def describe(self): return f"This color has the value {self.value}"
C++ enum
Features
- Integral Underlying Type: In C++, the values of enum members are restricted to integral types, although you can specify which one (e.g.,
char,int). - Scoped (or
enum class): Introduced in C++11,enum classprovides better type safety and scope management compared to traditional enums. - Conversions: Traditional C++ enums can be implicitly converted to integers, but
enum classmembers can’t without explicit casting.
Applications & Examples
- Basic Enumeration:
enum Color { RED, GREEN, BLUE }; - Scoped Enum with Specific Underlying Type:
enum class Color : char { RED = 'r', GREEN = 'g', BLUE = 'b' }; - Access and Comparisons:
Color col = Color::RED; if (col == Color::RED) { // Do something } - Custom “Enum” Using Classes:
class Color { public: static const Color Red() { return Color("Red"); } // ... Other colors and methods ... private: explicit Color(std::string value) : value_(value) {} std::string value_; };