Search code examples
pythonpython-3.xooppython-class

Python Object return a list


I have a Deck class from which i create a deck Object:

class Deck:
  cards = []

deck = Deck()

How can I make the deck object to return the cards list when called?

print(deck)

# or

for card in deck:
  # do

Without having to always call deck.cards?


Solution

  • You could define __iter__ in class Deck:

    class Deck:
        def __init__(self):
            self.cards = [1, 2, 3]
    
        def __iter__(self):
            for i in self.cards:
                yield i
    
    
    deck = Deck()
    for card in deck:
        print(card)
    

    And this print:

    1
    2
    3