3 ms·
Can someone help me understand how this helps? I'm only a mediocre programmer, and I'm having trouble understanding the implications. It seems like you declare
by e1ven 13y ago
Can someone help me understand how this helps?
I'm only a mediocre programmer, and I'm having trouble understanding the implications.
It seems like you declare these like any other class.
So what's the difference between this, and creating a class full of ints?
If I have class Color:
red = 1
blue = 2
etc, wouldn't I get the same thing?
Is the difference that you don't need to instantiate an instance of it?
I know I'm being dense, and I've read the PEP, but it's not quite clicking yet.
- famousactress 13y agoIn this case, the attributes are not ints.. so If you defined that class functions that took it's attributes would need to accept an int, and if I passed max-int or something it'd be up to your function to go figure out whether my argument was a valid value for Color. The enum class gives you that stuff. The argument you'd expect would be instanceof(arg, Color) == True (I think that's how they did it) and if it was, you'd be assured that the value was a valid value for Color. So you could do it yourself, sure.. but to get all the little benefits, you'd have to do more coding than naming a bunch of ints in a new class.. It's subtle though. Not a wild game-changer or anything :)
- e1ven 13y agoThanks.. That makes sense.. And I suppose it also helps satisfy the "explicit is better than implicit" edict, by making it clearer what you are doing.
- pyre 13y agoRead the section on IntEnums[1]: IntEnum values behave like integers in other ways you'd expect: >>> int(Shape.circle) 1 >>> ['a', 'b', 'c'][Shape.circle] 'b' >>> [i for i in range(Shape.square)] [0, 1] [1] http://www.python.org/dev/peps/pep-0435/#intenum http://www.python.org/dev/peps/pep-0435/#intenum
- dietrichepp 13y agoIn addition to what famousactress said, you also get: >>> Color.red <Color.red: 1> So when you print out an enumeration, you get its name instead of just the number. This can be a big deal for debugging e.g. OpenGL code, which has a lot of enumerations. Which of the following would you prefer? >>> gl.getError() 1286 Or would you prefer, >>> gl.getError() <gl.INVALID_FRAMEBUFFER_OPERATION: 1286>