Last answered:

10 Mar 2024

Posted on:

26 Apr 2021

0

Resolved: How to make print(card) display full words instead of inputted words?

For the question on creating a playing card class, at the end of the lecture we were asked to make the code print out for example "Ace of hearts" if we inputted (1, 'h'). I tried to write the code but I am getting error messages.

This is my code:
image
and this is the error I'm getting:
image

2 answers ( 1 marked as helpful)
Instructor
Posted on:

27 Apr 2021

0

Hi Mohamed,

It appears you have stumbled upon the difference between class variables and instance variables.
------------------------------------------
Basically, instance variables are those variables that are unique to each instance of a class.
In the example task, there are 2 class variables - self.value and self.suit; you can recognise such variables (or, indeed,
designate them as such) by prepending them with self. If you are to create multiple instances of Card, these variables
would differ accordingly:

card_7_spades = Card(7,'s')   ## card_7_spades.value = 7 , card_7_spades.suit = 's'
card_J_hearts = Card(11, 'h') ## card_J_hearts.value = 11 , card_J_hearts.suit = 'h'

Notice that using get_suit() or get_value() would yield more meaningful results.
------------------------------------------
On the other hand, class variables are shared by all instances of the class. In the example, the dictionaries suits and values
'aspire' to be such class variables. This, however, results in errors, because mutable Python objects cannot act as
class variables. Either you have to define your dictionaries outside of the class to use them, or transform them into
instance variables (for example, having self.values = {...} and so on).
------------------------------------------
You could also benefit from looking at the official Python documentation on the matter (https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables).
---
Regards,
A., The 365 Team

Posted on:

10 Mar 2024

0

class Card:

    suits={'s':"Spades",'h':"Hearts", 'c':"clubs", 'd':"Diamonds"}
    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, suit, value):
        self.suit=suit
        self.value= value

    def get_suit(self):
        return self.suits[self.suit]

    def get_value(self):
        return self.values[self.value]


    def __str__ (self):
        charc = self.get_value()+' in '+ self.get_suit()
        return charc

Submit an answer