【问题标题】:Python OOP object printing properties problemPython OOP 对象打印属性问题
【发布时间】:2019-02-21 15:56:55
【问题描述】:

所以当我尝试形成一个 Pile 类时,我正在开发一个纸牌游戏,我在其中构建了一个函数来打印卡片类中的卡片和堆类中的卡片列表。当我尝试在桩类中使用卡片类(在其他类中工作)中的函数时,我没有得到预期的结果。我该如何解决这个问题?

卡类:

import random
from Enums import *

class Card:
    def __init__(self):
        self.suit = Suit.find(random.randint(1, 4))
        self.rank = Rank.find(random.randint(1, 14))

    def show(self):
        print (self.rank.value[1], "of", self.suit.value[1])

桩类:

from Enums import *
from Card import *
from Hand import *

class Pile:
    def __init__(self):
        self.cards = []
        self.cards.append(Card())

    def discard(self, hand, card):
        self.cards.append(card)

        if (not searchCard(self, hand, card)):
            print ("The card was not found, please select another one or cheat")
            return True
        else:
            return False

    def takePile(self, hand):
        for x in self.cards:
            hand.cards.append(self.cards[x])

    def clearPile(self):
        while len(self.cards) > 0:
            self.cards.pop()

    def searchCard(self, hand, card):
        flag = False

        for x in hand.cards and not flag:
            if (hand.cards[x].rank.value[0] == card.rank.value[0]):
                if (hand.cards[x].suit.value[0] == card.suit.value[0]):
                    hand.cards[x].pop()
                    flag = True

        return flag

    def showCurrent(self):
        for x in self.cards:
            x.show()

我指的是 Card 类中的 show 函数和 Pile 类中的 showCurrent 和 init

当我运行游戏和线路时

print ("It's your turn now, the pile presents a", pile.showCurrent())

我从 Card 类的 show 函数中得到一个 None 而不是 print,如下所示:

现在轮到你了,一堆没有

【问题讨论】:

  • 嗯,您正在打印showCurrent() 的结果,即None。只需在print之后调用showCurrent,然后它应该可以按预期工作。
  • 你能用 str 函数代替显示答案吗?
  • 另外,从打印的消息来看,showCurrent 似乎应该只打印最上面的卡片,但它会打印所有卡片。
  • 但我也使用 show 功能,所以它必须使用它并打印那里的内容
  • 一般来说,保持 I/O 尽可能靠近程序的“边缘”。如果您可以在现在打印某些内容和返回一个字符串以供 else 打印之间做出选择,请选择后者。

标签: python list function oop printing


【解决方案1】:

主要问题是您正在打印showCurrent() 的结果,即None。要解决此问题,只需将调用 showCurrent 移出 print

print("It's your turn now, the pile presents a")
pile.showCurrent()

此外,您可能希望将您的 show 方法更改为正确的 __str__ 方法,以使其更加通用。您也必须更改 showCurrent 方法:

# in class Card:
def __str__(self): # just return the formatted string here
    return "%s of %s" % (self.rank.value[1], self.suit.value[1])

# in class Pile:
def showCurrent(self): # print the string here
    for x in self.cards:
        print(x) # this calls str(x), which calls x.__str__()

但是您的消息表明您实际上只想打印最上面的卡片,而不是整个堆栈。使用__str__,您现在可以直接在print 调用中执行此操作:

print("It's your turn now, the pile presents a", pile.cards[0]) # calls __str__

【讨论】:

  • 您可能想在__str__ 中使用%s,而不是%r
  • @chepner 对,已修复。
猜你喜欢
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 2020-01-02
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多