We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Polymorphism Practice

Let's continue working on the card game we started in an earlier practice problem. Let's add some logic to our Card class to simplify comparing one instance of a Card to another.

Ranking Cards

To compare two cards, we need a set of rules.

  1. The rank (value) of the card (2, 3... King, Ace) is the primary comparison. A "King" is always greater than a "Queen", regardless of suit.
  2. Only if the ranks are identical do we look at the suit (Clubs, Diamonds, Hearts, Spades).
  3. The global lists RANKS and SUITS define the order. The higher the index, the higher the value.
  • Card("Ace", "Hearts") > Card("Queen", "Hearts") is True because "Ace" has a higher index than "Queen".
  • Card("King", "Spades") > Card("King", "Hearts") is True because "Spades" comes after "Hearts" in the SUITS list.

Assignment

Complete the Card class:

    • You will need the indexes of the ranks, and suits to help you compare them against each other. Keep in mind that a rank and a suit are just strings within a list.

The .index list method is very useful when trying to determine the index of an element in a list.

For __eq__, check that other is a Card before reading its indexes. Python's isinstance(other, Card) is the usual way to do that.