class / instance question

Ben Finney bignose+hates-spam at benfinney.id.au
Thu Mar 22 22:10:53 EDT 2007


belinda thom <bthom at cs.hmc.edu> writes:

> I've written two game classes---Nim and TicTacToe---where each
> derives from a Game class that I've created (it is essentially an
> abstract base class, where I've used an "abstract()" hack to
> somewhat enforce this).

You can use the 'NotImplemented' built-in object, or the
'NotImplementedError' exception, for this purpose:

    class BaseFoo(object):
        """ Abstract base class for Foos """
        def bar(self):
            """ Method which must be overridden in subclass """
            raise NotImplementedError("bar() must be overridden")

    class FrobulatingFoo(BaseFoo):
        """ A Foo that frobulates """
        def bar(self):
            print "Frobulating..."
            print " done."

> I now want to be able to pass either of these classes into a game-
> playing engine, for instance a function
>
> playGame(classOfGameToBePlayed) :
>     # inside of which I create a new game using that class's constructor
>
> Is this possible, and if so, how to approach it?

It works just as you describe. The class is an object, that can be
passed as an argument just like any other object. That object is
callable, and invokes the class constructor to return a new instance
of the class.

    def play_game(game_class):
        """ Play a new game """
        game = game_class()
        game.start_play()

-- 
 \        "The number of UNIX installations has grown to 10, with more |
  `\     expected."  -- Unix Programmer's Manual, 2nd Ed., 12-Jun-1972 |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list