首页 > 解决方案 > Python OOP 对象打印属性问题

问题描述

因此,当我尝试形成一个 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 ,如下所示:

现在轮到你了,一堆没有

标签: pythonlistfunctionoopprinting

解决方案


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

推荐阅读