outputting object of class instead of value | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

outputting object of class instead of value

I can't figure out the next steps in order to correctly output the deck of cards. Instead, I'm getting a list of <__main__.Card object at 0x100a93cd0> can someone give me some guidance. Im new to classes and I'm sure this is pretty simple. Appreciate any help class Card: def __init__(self, value, color): self.value = value self.color = color colors = ['heart', 'diamonds', 'spades', 'clubs'] deck = [Card(value, color) for value in range(1, 14) for color in colors]

3rd Aug 2022, 12:38 AM
David
David - avatar
8 Answers
+ 2
David, Apparently __repr__ dunder is the one we were looking for ... def __repr__( self ): return f"{self.color} {self.value} Card"
3rd Aug 2022, 8:23 AM
Ipang
+ 3
David, Line 8 should be returning a string return f"{self.value}, {self.color}" But even after applying that change, print( deck ) still only displays raw object info ... A for...in loop however, appears to be working, as in it calls the __str__ dunder so we see what the dunder return when printing the object ...
3rd Aug 2022, 1:12 AM
Ipang
+ 2
Maybe add a __str__ dunder to make the object printable? Or did I misunderstand you completely?
3rd Aug 2022, 12:55 AM
Ipang
3rd Aug 2022, 1:03 AM
David
David - avatar
+ 1
Ipang you mean like this: def __str__(self): return self.value, self.color I try this then tried prting the deck and im still getting the object
3rd Aug 2022, 12:59 AM
David
David - avatar
+ 1
David, Please share the code bit link so we can see the whole picture ...
3rd Aug 2022, 1:00 AM
Ipang
+ 1
Ipang i just dont know how to create an instance of the class when the parameters are being used in the for loop. Basically i just want to create deck of cards using a class. If you think there is a better way i will certainly try it.
3rd Aug 2022, 1:08 AM
David
David - avatar
+ 1
Ipang i try this but i forgot to fix my return to f”{}{}”. Instead i was still using return self.color, … really appreciate your help
3rd Aug 2022, 1:28 PM
David
David - avatar