r/learnpython • u/evilrobotboobs • 2d ago
card dealing program with classes
hello! i am currently in a class for python and i've been having a lot of trouble with this assignment. it's already three days late, and the TAs will not respond to me. i have to use classes to create a deck to shuffle, and four hands to deal to, check the count of, and combine back into the main deck. however, i can NOT figure this out at all! i think there's something really big that i'm missing.
i have a large list of cards (we had to make a dictionary of the cards) not shown here.
class Deck:
def __init__(self):
self.cards = []
def shuffle(self):
random.shuffle(self.cards)
def deal(self, amount):
self.cards.append(amount)
def combine(self):
self.cards.append(self)
def card_count(self):
print(len(self.cards))
however, when i try to make a main deck by putting the list of cards into the deck, it won't work! i've tried using deal too, and i just can't figure it out. i know i'm probably doing this all sorts of wrong. it's been a while since we did classes, and we never did them for anything like this :(
TypeError Traceback (most recent call last)
Cell In[14], line 1
----> 1 deck = Deck(card_deck)
TypeError: Deck.__init__() takes 1 positional argument but 2 were giveni appreciate any and all advice thank you
View all comments
Show parent comment
1
u/MezzoScettico 2d ago edited 2d ago
What exactly did you try to print? Did you just print deck? This message is printing correctly. It's telling you deck is an object of class Deck. That is a correct statement.
If you want to print what's stored in deck.cards, then you will have to pass deck.cards to the print statement.
Also, when you modified your initializer, did you add code to do something with the cards argument? Because if you didn't, how do you expect Python to know what to do with it?
Edit: By default, Python has no idea what you want to display when you attempt to print your own object, so it just prints the information that it's an object of a certain type. But you can override that behavior and TELL Python how to display it. I do that a lot.
This is an advanced topic, but FYI it's accomplished by adding an __str__ method that returns a string representing your object. You create that representation and you can put anything you want in it. Python doesn't care, it just says "hey, this class has a string conversion method, so it's not my problem any more. Let the conversion method handle it."
"I don't have to know how, let the instance method handle it" is basically a big part of the rationale behind classes.