【问题标题】:How does a Python class within another class work w/o Inheritance? (Python Beginner)另一个类中的 Python 类如何在没有继承的情况下工作? (Python初学者)
【发布时间】:2019-11-16 13:51:04
【问题描述】:

我是一个 python 初学者,刚跑完扔了一本书,其中包括这个 MiniProject。练习内容如下:

你的任务是创建一副纸牌类。卡片组类应该在内部使用另一个类,一个卡片类。您的要求是:

  • Deck 类应该有一个发牌方法,可以用牌组中的一张牌发牌
  • 发牌后,将其从牌堆中移除
  • 应该有一种洗牌方法,确保一副牌有所有 52 张牌,然后随机重新排列它们
  • Card 类应该有花色(红心、方子、梅花、黑桃)和值(A、2、3、4、5、6、7、8、9、10、J、Q、K)

提供的解决方案如下:

from random import shuffle

class Card:
    def __init__(self, suit, value):
        self.suit = suit
        self.value = value

    def __repr__(self):
        return "() of ()".format(self.value, self.suit)


class Deck:
    def __init__(self):
        suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
        values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
        self.cards = [Card(suit, value) for suit in suits for value in values]

    def __repr__(self):
        return "Cards remaining in deck: ()".format(len(self.cards))

    def shuffle(self):
        if len(self.cards) < 52:
            raise ValueError("Only full decks can be shuffled")
            shuffle(self.cards)
            return self

    def deal(self):
        if len(self.cards) == 0:
            raise ValueError("All cards have been dealt")
            return self.cards.pop()

Q1:我可以遵循个别方法,但不知道如何正确使用它。

我尝试将Card 类与:

card = Card("Diamonds", "K")
print(card)

上面的输出是:() of ()

Q2:__repl__ 是如何工作的,我们如何称呼它?

我对长度感到抱歉。我感谢任何有关此问题的帮助和时间。非常感谢任何关于如何解释正在发生的事情的额外清晰度。

【问题讨论】:

    标签: python-3.x class


    【解决方案1】:
    card = Card("Diamonds", "K")
    print(card)
    

    这个最终代码是正确的。 repr 方法是一个特殊的内置函数,它定义了对象如何被 REPResented,例如 print 函数将显示什么。

    我的想法是print(card)等价于print(card.__repr__())

    您遇到的问题是您的 repr 方法存在问题。它们应该如下所示:

    • 卡片
    def __repr__(self):
            return "{} of {}".format(self.value, self.suit)
    
    • 甲板
    def __repr__(self):
            return "Cards remaining in deck: {}".format(len(self.cards))
    

    我还会更改 shuffle 和 deal 函数,因为它们会产生无法访问的代码警告。避免在引发错误后将代码放在同一块中。

    def shuffle(self):
        if len(self.cards) == 52:
            shuffle(self.cards)
            return self
        else:
            raise ValueError("Only full decks can be shuffled")
    
    def deal(self):
        if len(self.cards) != 0:
            return self.cards.pop()
        else:
            raise ValueError("All cards have been dealt")
    

    【讨论】:

      【解决方案2】:
      from random import shuffle
      
      class Card:
          def __init__(self, suit, value):
              self.suit = suit
              self.value = value
      
          def __repr__(self):
              return "(%s,%s)" %(self.value, self.suit)
      
      
      class Deck:
          def __init__(self):
              suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
              values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
              self.cards = [Card(suit, value) for suit in suits for value in values]
              for i in self.cards:
                  print(i)
      
          def __repr__(self):
              return "Cards remaining in deck: {}".format(len(self.cards))
          
          def shuffle(self):
              if len(self.cards) == 52:
                  shuffle(self.cards)
                  return self.cards
              else:
                  return("Only full decks can be shuffled")
      
          def deal(self):
              if len(self.cards) != 0:
                  return self.cards.pop()
              else:
                  return("All cards have been dealt")
      
      d=Deck()
      print("Deck created")
      
      print("\n \nShuffling the deck")
      x=d.shuffle()
      for i in x:
          print(i)
      a=int(input("\n \nEnter 1 to deal the cards \n"))
      
      while(a==1):
          print(d.deal())
          print(d)
          a=int(input("Enter 1 to deal the cards (or) any key to discontinue \n"))
      print(d.shuffle())
      

      【讨论】:

        猜你喜欢
        • 2022-08-02
        • 2021-12-19
        • 1970-01-01
        • 2015-11-25
        • 2021-04-08
        • 1970-01-01
        • 2013-05-19
        • 1970-01-01
        • 2022-11-16
        相关资源
        最近更新 更多