Trying to map instance variables to a dictionary within a class

Viewed 76

New to SO, and learning Python.

I'm trying to create a class so that when an instance of the class is instantiated, the arguments the user inputs are mapped to a class dictionary, and values are taken from the dictionary and stored in the instance variables instead of the arguments the user specified. Here's my code:

class Card(object):
    '''This class sets up a playing card'''
    
    suits = {'d':'diamonds', 'h':'hearts', 's':'spades', 'c':'clubs'}
    values = {1:'Ace',2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King'}
    
    def __init__ (self, value, suit):
        self.value = value
        self.suit = suit
        
    def get_value(self):
        return values[self.value]
    
    def get_suit(self):
        return self.suit
    
    def __str__(self):
        my_card = str(self.value) + ' of ' + str(self.suit)
        return my_card

So, if I were to type:

my_card = Card (1,'d')

And then, call the get_value method I made it would return 'Ace'

And if I were to call the get_suit method it would return 'diamonds'

And if I printed my_card, it would print: Ace of diamonds

Does anyone know how to do this?

2 Answers

You are very, very close with what you have already.

Since the values and suits are attributes of the Card class, you need to access them using the same self. notation.

So, your Card class would look like this (comments above lines I changed):

class Card(object): 
    '''This class sets up a playing card'''
    suits = {'d':'diamonds', 'h':'hearts', 's':'spades', 'c':'clubs'}
    values = {1:'Ace',2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King'}

    def __init__ (self, value, suit):
        self.value = value
        self.suit = suit

    def get_value(self):
        # Access the values dictionary with self.values
        return self.values[self.value]

    def get_suit(self):
        # Same thing for suits!
        return self.suits[self.suit]

    def __str__(self):
        # Changed the accessor for suits to be complete
        my_card = str(self.value) + ' of ' + str(self.suits[self.suit])
        return my_card

Alternatively for your __str__ you could have

def __str__(self):
    return self.get_value() + ' of ' + self.get_suit()

Honestly you got everything you need... just need to put the pieces together in the right way.

class Card():
    def __init__ (self, value, suit):
            self.value = value
            self.suit = suit
            self.suits = {'d':'diamonds', 'h':'hearts', 's':'spades', 'c':'clubs'}
            self.values = {1:'Ace',2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King'}

    def __str__(self):
            my_card = '{} of {}'.format(self.values[self.value], self.suits[self.suit])
            return my_card
my_card = Card(1, 'd')
print(my_card)
Related