[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Python enumerations



Dan <dan@xxxxxxxxxxxxxxxx>:
>
> There seem to be lots of ways of implementing enumerations in Python.

Indeed. It seems that the only real "canon" enum in Python is bool.
Perhaps one could emulate that if one wanted a custom enum?

I.e., something like:

  class enum(int):
      def __new__(cls, num, repr):
          obj = int.__new__(cls, num)
          obj.__repr = repr
          return obj
      def __repr__(self):
          return self.__repr

You could then either define all the enum values "manually", or create
some fancy mechanism for it.

  >>> red = enum(0, 'red')
  >>> green = enum(1, 'green')
  >>> yellow = enum(2, 'yellow')
  >>> red
  red
  >>> green + yellow
  3

You could also create a factory wrapper around it, so that you could
create different enum instances with internal counters. Then you could
do things like:

  >>> color = enum()
  >>> red = color('red')
  >>> red + 1
  1

And so forth...

-- 
Magnus Lie Hetland                    Fall seven times, stand up eight
http://hetland.org                                  [Japanese proverb]