Python OOP对象打印属性问题

时间:2019-02-21 15:56:55

标签: python list function oop printing

因此,当我尝试形成桩类时,我正在玩纸牌游戏,在此我构造了一个函数来打印卡类中的卡和桩类中的卡列表。当我尝试使用桩类中的卡片类(在其他类中使用过)的功能时,没有得到预期的结果。我该如何解决?

卡类:

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函数,而桩类中是showCurrent和init。

当我运行游戏和线条时

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

我从Card类中的show函数获得None而不是打印内容,如下所示:

现在轮到您了,一堆没有礼物

1 个答案:

答案 0 :(得分:3)

主要问题是您正在打印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__