Simple color class example
Sep 15th, 2009 02:23
jick heir, Nathan Wallace, Hans Nowak, Snippet 94, Tim Peters
> Has anyone given thought to sum types (or enumerations to the C people)?
> Something like:
> >>> type color: Red, Green, Blue
> >>> Red
> >>> type(Green)
> <type 'color'>
> I suppose I could make a bunch of empty classes like:
> class color: pass
> class Red(color): pass
> class Green(color): pass
> class Blue(color): pass
> and then use isinstance() but that's not very pretty.
I usually do
RED, GREEN, BLUE = range(3) # RED==0, GREEN==1, etc
There are any number of ways to do fancier stuff using classes, but don't
think I ever found them worth the (minimal!) effort. E.g., more pleasant
than the above is probably:
def __init__(self, name):
self.name = name
# define equality and hashing assuming object
# identity is desired (as opposed to e.g. equality
# of color names)
def __cmp__(self, other):
return cmp(id(self), id(other))
def __hash__(self, other):
return isinstance(thing, Color)
RED = Color("Red")
GREEN = Color("Green")
BLUE = Color("Blue")
red, green, blue = "red", "green", "blue"
this = Color.red
if this in (Color.blue, Color.green):
print "ooops!", this
Or define red, green & blue as module attributes in Color.py. Etc.
If you want to do a lot of this, you can write higher-level classes to
automate the repetition in whatever scheme suits you best. But I predict
you'll drop it once the novelty wears off <0.9 wink>.