Entry
Simple color class example
Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 94, Tim Peters
"""
Packages: oop;miscellaneous
"""
"""
> Has anyone given thought to sum types (or enumerations to the C people)?
> Something like:
>
> >>> type color: Red, Green, Blue
> >>> Red
> 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:
"""
class Color:
def __init__(self, name):
self.name = name
def __str__(self):
return 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 hash(id(self))
def isColor(thing):
return isinstance(thing, Color)
RED = Color("Red")
GREEN = Color("Green")
BLUE = Color("Blue")
"""
Even simpler,
"""
class Color:
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>.
"""