python - 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 ,如下所示:
现在轮到你了,一堆没有
解决方案
主要问题是您正在打印 的结果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__
推荐阅读
- android - 需要单击两次才能更新文本视图中的文本
- javascript - 切换布尔值反应
- python - Jupyter Notebook 中的 PySpark:“列”对象不可调用
- vba - 制作组合框选择控制形状Powerpoint VBA的可见性/不可见性
- augmented-reality - RealityKit 中的 Entity 和 ModelEntity 有什么区别?
- laravel - 将 750 行添加到 Datatables rows().add()
- spring-boot - 为什么我使用 sec:authorize ="isAnonymous()" 在导航栏上获得两个 MY ACCOUNT
- jquery - 日期选择器的日期搜索无法传递给控制器
- ckan - 如何查看 CKAN 实体的 ID(和“名称”)(用于 API 更新调用)?
- android - 已关闭:Android:使用 com.google.android.material 低于 android 9 (sdk 29) 时应用程序不断崩溃