Spot any errors? let me know, but Unleash your pedant politely please.

Monday 18 May 2009

Example of an exception class in Python

If I'm going to suggest that you define your own exceptions, I really ought to give an example:

class PlayerError(Exception):
    pass

class PlayerIsNotPlayingInExpectedDirectionError(PlayerError):
    def __init__(self, direction):
        """direction parameter should be 'forwards' or 'in reverse'"""
        if 'rev' in direction : direction = 'in reverse'
        self.direction = direction

    def __str__(self):
        return "Player was not playing %s as expected." % self.direction

No comments:

Post a Comment