Created
January 2, 2014 22:52
-
-
Save GuillermoBlasco/8228679 to your computer and use it in GitHub Desktop.
Simulation of enums for python 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Simulation of enums for python 2.x | |
class Enum(object): | |
def __init__(self, **kwargs): | |
for key, value in kwargs.iteritems(): | |
setattr(self, key, value) | |
self._asDict = dict(kwargs) | |
def __contains__(self, item): | |
return item in self._asDict.values() | |
def __iter__(self): | |
return self._asDict.values().__iter__() | |
def __getitem__(self, key): | |
return self._asDict[key] | |
def __add__(self, other): | |
if not isinstance(other, Enum): | |
raise ValueError("Expected enum object to sum") | |
return Enum(**dict(self._asDict.items() + other._asDict.items())) | |
def __str__(self): | |
return str(self._asDict) | |
e1 = Enum(ONE = 1, TWO = 2) | |
e2 = Enum(THREE = 3) | |
print e1+e2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment