python-3.xstringclass-attributes

Accessing class attributes in __str__ method in Python


I am making a card class in Python 3.x. I am trying to utilize the __str__ method to print the card.

class Card:

    ranks = ["Ace", "Two", "Three", "Four", "Five", "Six",
             "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]

    def __init__(self, rank=-1, suit=-1):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        if self.rank != -1 and self.suit != -1:
            return "{0} of {1}".format(ranks[self.rank], suits[self.suit])
        else:
            return "Null"

print(Card(1, 0))

My program should print Two of Clubs.

Instead, I receive: NameError: name 'ranks' is not defined. Did you mean: 'range'?

It seems you cannot access class attributes this way in Python, so, how can I properly customize the string representation of my instances?

Thanks!


Solution

  • Add Card. or self. to ranks and suits:

    class Card:
    
        ranks = ["Ace", "Two", "Three", "Four", "Five", "Six",
                 "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
        suits = ["Clubs", "Diamonds", "Hearts", "Spades"]
    
        def __init__(self, rank=-1, suit=-1):
            self.rank = rank
            self.suit = suit
    
        def __str__(self):
            if self.rank != -1 and self.suit != -1:
                return "{0} of {1}".format(Card.ranks[self.rank], Card.suits[self.suit])
            else:
                return "Null"
    
    print(Card(1, 0))
    

    Prints:

    Two of Clubs