Search code examples
pythonlistclassplaying-cards

python class cant find its own attribute


I tried to create classes to represent a deck of cards. The problem is that the showDeck method doesn't find the cards list and prints out:

Traceback (most recent call last):
  File "C:\Users\User\workspace\learn\cards\Deck.py", line 32, in <module>
    newDeck.showDeck()
  File "C:\Users\User\workspace\learn\cards\Deck.py", line 27, in showDeck
    for item in self.cards ():
AttributeError: 'Deck' object has no attribute 'cards'

here is the code:

class Card:
    def __init__(self,sign,number):
        self.number=number  
        self.sign=sign
   #constructor of card class

    def show (self):
        print ("["+str(self.sign)+","+str(self.number)+"]")
    #prints out the card  

class Deck:
    def _init_ (self):
       self.cards=[]
       for i in range (1,4):
           sign=i
           for i in range (1,14):
               number=i
               a=Card(sign,number)
               a.show()
               self.cards.append(a)
     #the constructor of the deck, creates a list, and then creats all the possible cards and adds them to the list          

    def showDeck (self):
        for item in self.cards ():
            item.show
    #prints out the deck

newDeck= Deck()

newDeck.showDeck()

Solution

  • You misspelled the Deck.__init__ method:

    class Deck:
        def _init_ (self):
    

    You need two underscores at the start and end. Your _init_ method is never called, so self.cards is never set.

    You have it correct for the Card class; notice how the number of underscores is double on both sides of the init?

    class Card:
        def __init__(self,sign,number):