所以我正在开发一个纸牌游戏,当我尝试形成一个 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 而不是打印,如下所示:
现在轮到你了,堆里呈现的是 None
最佳答案
主要问题是您正在打印 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__
关于Python OOP对象打印属性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54811226/