How to do it...

  1. Define the essential class:

        class Card: 
            __slots__ = ('rank', 'suit') 
            def __init__(self, rank, suit): 
                self.rank = rank 
                self.suit = suit 
            def __repr__(self): 
                return "{rank:2d} {suit}".format( 
                    rank=self.rank, suit=self.suit 

We've defined a generic Card class that is suitable for ranks two to ten. We've included an explicit call to any superclass initialization via super().__init__().

  1. Define any subclasses to handle specializations:

        class AceCard(Card): 
            def __repr__(self): 
                return " A {suit}".format( 
                    rank=self.rank, suit=self.suit 
        class FaceCard(Card): 
            def __repr__(self): 
                names = {11: 'J', 12: 'Q', 13: 'K'} 
                return " {name} {suit}".format( 
                    rank=self.rank, suit=self.suit, 

Get Modern Python Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.