holaprofesor
holaprofesor

Reputation: 271

.__repr__() help python 3

I am creating a class definition for a playing Card. A playing card needs to store information about its suit (clubs, diamonds, hearts, or spades) and rank (2-10, jack, queen, king, or ace). My next step, which is creating a .__repr__() method, is giving me trouble. I know that it will be similar to my .__str__ method, but the __repr__ method still gives me trouble. This is what I have so far:

class Card:
"""a class for determining suit and rank of a card in a 52-card deck

attributes: suit(x) and rank(y)"""
    def __init__(self, suit, rank):
        """assigns values to the appropriate attributes

        str, str -> str"""
        self.x = rank
        self.y = suit
    def __str__(self):
        """creates a str for appropriate display of cards"""
        if not isinstance(self.x,int):
            if self.x == "J" or self.x == "j":
                x = "Jack"
            elif self.x == "Q" or self.x == "q":
                x = "Queen"
            elif self.x == "K" or self.x == "k":
                x = "King"
            elif self.x == "A" or self.x == "a":
            x = "Ace"
        else:
            x = str(self.x)

        if self.y == "D" or self.x == "d":
            y == "Diamonds"
        elif self.y == "H" or self.x == "h":
            y == "Hearts"
        elif self.y == "S" or self.x == "s":
            y == "Spades"
        elif self.y == "C" or self.x == "c":
            y == "Clubs"
        return x + " of " + y

    def __repr__(self):
        """returns a str that could be used as a command by python"""
        return self.x + 'of' + self.y

Upvotes: 1

Views: 488

Answers (1)

For the repr that could be used as a Python expression, well, it should return a string having format Card('D', 'J'), with repr of the self.suit and self.rank respectively (fixed their names for you!) into their repr representation.

This is easy by using the % formatting operator:

def __repr__(self):
    return 'Card(%r, %r)' % (self.suit, self.rank)

Now

print(repr(Card('D', 9)))

will output

Card('D', 9)

On a related note, instead of testing the given suit and rank for both lower and upper case letters, just convert them to upper case in your constructor:

if isinstance(rank, str):
    self.rank = rank.upper()
else:
    self.rank = rank

self.suit = suit.upper()

Now you just need to test for their upper case variants. Though I'd never recommend mixing int and str for such value; either number the cards 1-13 or 2-14 or so, or use strings for all ranks.

Upvotes: 3

Related Questions