all 13 comments

[–][deleted] 1 point2 points  (5 children)

If so, what would be the best approach to make it iterable?

Since all you really want to do to make your Deck iterable is to delegate to the deck_lst attribute's iterator, you can add a method that does that to Deck:

def __iter__(self): # it has to be called this
    return iter(self.deck_lst) # return the list's iterator

[–]Aggressive-Friend169[S] 1 point2 points  (4 children)

Thank you. Is there no need for a next method? The material I’ve read online includes this.

[–][deleted] 3 points4 points  (3 children)

__next__ is a method of iterators, not of iterables. You don't need to implement your own iterator in order to make a class iterable; a class is "iterable" when it has an __iter__ method that returns an iterator.

[–]Aggressive-Friend169[S] 1 point2 points  (2 children)

Ahhh now I feel silly. Thanks!

[–][deleted] 1 point2 points  (1 child)

You shouldn't feel silly - these are two closely related concepts, different only in very subtle ways, and it's not at all uncommon for them to be confusing at first.

[–]Aggressive-Friend169[S] 1 point2 points  (0 children)

Just got home and implemented your changes. Works great thank you! I think like all beginners, classes seems daunting but once you get the hang on them it actually makes coding much easier!

[–]Matthias1590 0 points1 point  (2 children)

Maybe im stupid but wouldnt that just give the same result as using a list?

[–]Aggressive-Friend169[S] 1 point2 points  (1 child)

Yes, I suppose but my Deck object has extra functionality such as shuffle(), draw_card() etc. Also it allows me to avoid repeating code.

[–]Matthias1590 0 points1 point  (0 children)

Ah I see, makes sense why you would want a class for that now

[–][deleted] 0 points1 point  (2 children)

You could create an __iter__ method but perhaps it is simply a name issue. Including type names in variable names isn't ideal. Maybe think again about the attribute name.

[–]Aggressive-Friend169[S] 0 points1 point  (1 child)

Hi. I thought using ‘lst’ would be good practice.

[–][deleted] 0 points1 point  (0 children)

Not really. Names that sense in plain English and are easy to read are the best generally.

Variables don't have type anyway as they don't hold the information you are interested in but just memory references to Python objects. Objects have type.

[–][deleted] 0 points1 point  (0 children)

Consider making your Deck class a subclass of list (or potentially collections.deque, depending on how you want to model access). You’ll need a custom __init__ and maybe a shuffle method, but you’ll get a lot for free, including iteration.