I am writing this class to eventually create a playing card game (Spades) and also to utilize the object oriented paradigm. This was my attempt to model a card as an object. Each card has a suit and a rank that have each been given a specific weight that can be modified to fit the needs of the game. I have had several thoughts on how to implement this code differently, I thought about collapsing the weight system I had into a 1 - to 52 type system, or defining a dictionary where all cards assigned a value etc. However I decided to keep what I currently have as I feel this may yield greater flexibility to be expanded across several games. Last note, I decided to employ the Joker identity as a catch for cards that fall outside the expected input.
class Card(object): """Models a playing card, each Card object will have a suit, rank, and weight associated with each. possible_suits -- List of possible suits a card object can have possible_ranks -- List of possible ranks a card object can have Suit and rank weights are initialized by position in list. If card parameters are outside of expected values, card becomes joker with zero weight """ possible_suits = ["Clubs", "Hearts", "Diamonds", "Spades"] possible_ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"] def __init__(self, suit, rank): if suit in Card.possible_suits and rank in Card.possible_ranks: self.suit = suit self.rank = rank self.suit_weight = Card.possible_suits.index(suit) self.rank_weight = Card.possible_ranks.index(rank) else: self.suit = "Joker" self.rank = "J" self.suit_weight = 0 self.rank_weight = 0 def __str__(self): """Returns abbreviated name of card Example: str(Card('Spades', 'A') outputs 'AS' """ return str(self.rank) + self.suit def __eq__(self, other): """Return True if cards are equal by suit and rank weight""" return self.suit_weight == other.suit_weight and self.rank_weight == other.rank_weight def __gt__(self, other): """Returns true if first card is greater than second card by weight""" if self.suit_weight > other.suit_weight: return True if self.suit_weight == other.suit_weight: if self.rank_weight > other.rank_weight: return True return False def modify_weight(self, new_suit_weight = None, new_rank_weight = None): """Modifies weight of card object""" if new_suit_weight: self.suit_weight = new_suit_weight if new_rank_weight: self.rank_weight = new_rank_weight def get_suit(self): return self.suit def get_rank(self): return self.rank def get_suit_weight(self): return self.suit_weight def get_rank_weight(self): return self.rank_weight