【问题标题】:python class cant find its own attributepython类找不到自己的属性
【发布时间】:2015-03-21 09:48:39
【问题描述】:

我尝试创建类来表示一副纸牌。 问题是showDeck方法没有找到卡片列表并打印出来:

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'

代码如下:

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()

【问题讨论】:

    标签: python list class playing-cards


    【解决方案1】:

    您拼错了Deck.__init__ 方法:

    class Deck:
        def _init_ (self):
    

    开头和结尾需要 两个 下划线。你的_init_ 方法永远不会被调用,所以self.cards 永远不会被设置。

    对于Card 类,您认为它是正确的;请注意init 两侧的下划线数量如何增加一倍?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2014-01-11
      • 2014-05-07
      • 1970-01-01
      相关资源
      最近更新 更多