I am trying to create a set of states for a class Node. I usually do this by setting each Nodeinstance variable stateto int, and a document that int matches what state (since I don't have enums).
This time I would like to try something else, so I decided to go with this:
class Node:
state1 = 1
state2 = 2
def __init__(self):
...
It works well. However, I ran into a problem when I have many states - too many to print manually. Also, with these many states, I can make a mistake and assign the same to the inttwo states. This would be a source of error in testing conditions (for example, if self.state==Node.state1may fail if Node.state1and Node.state2were 3).
For this reason, I would like to do something like this:
class Node:
def __init__(self):
...
...
for i,state in enumerate("state1 state2".split()):
setattr(Node, state, i)
Although this would fix human errors in assigning values to states, it is pretty ugly as class variables are set outside the class definition.
Is there a way to set class variables in a class definition this way? Ideally, I would like to do this:
class Node:
for i,state in enumerate("state1 state2".split()):
setattr(Node, state, i)
... but this will not work, as it Nodeis not yet defined, and will lead toNameError
Alternatively, does enumpython3.3 exist?
I'm on Python3.3.2 if that matters