class / instance question
bignose+hates-spam at benfinney.id.au
Fri Mar 23 03:10:53 CET 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:
""" Abstract base class for Foos """
""" Method which must be overridden in subclass """
raise NotImplementedError("bar() must be overridden")
""" A Foo that frobulates """
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.
""" Play a new game """
game = game_class()
\ "The number of UNIX installations has grown to 10, with more |
`\ expected." -- Unix Programmer's Manual, 2nd Ed., 12-Jun-1972 |
More information about the Python-list