r/learnpython • • 14d 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 given

i appreciate any and all advice thank you

1 Upvotes

16 comments sorted by

View all comments

2

u/MezzoScettico 14d ago edited 14d ago

I'll pile on with the specifics.

Look how you're creating an instance.

deck = Deck(card_deck)

So you're expecting to initialize it with a list of cards. Presumably it's supposed to save those cards as an attribute.

But then look how your class initializes it.

def __init__(self):
    self.cards = []

This initializer does not take an argument containing a list of cards. So there's a mismatch with how you're calling it.

The reason it says you called with 2 arguments even though "Deck(card_deck)" only looks like it has one, is that class instance methods always add "self" as an implied argument before any others.

With that in mind, what do you think should be between the parentheses in init(...)?

Edit: "class methods" was the wrong terminology for a specialized kind of thing you haven't encountered yet. I changed it to "instance methods".

2

u/evilrobotboobs 14d ago

presumably, something to do with cards... i have it as __init__(self, cards) now and it doesn't return an error anymore (yay!) but when i try to print it to check if it worked it gives me <__main__.Deck object at 0x74e12a5e70e0> (what!)

i was facing this issue yesterday and couldn't figure out my way past it, either

1

u/Boothiepro 14d ago

That looks correct! Every built in class does have their special __str__() defined to print something pretty and readable instead of its class and id. lists would also print <List object at id> it's just that the class List has a __str__() defined as for element in self: print(element)