Faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes
Recently 0 of 1 people (0%) answered Yes


Simple color class example

Sep 15th, 2009 02:23
jick heir, 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>.