我正在为扑克牌创建一个类定义。扑克牌需要存储有关其花色(梅花、方 block 、红心或黑桃)和等级(2-10、J、Q、K 或 A)的信息。我的下一步是创建一个 .__repr__()
方法,这给我带来了麻烦。我知道它会类似于我的 .__str__ 方法,但是 __repr__ 方法仍然给我带来麻烦。这是我到目前为止所拥有的:
class Card:
"""a class for determining suit and rank of a card in a 52-card deck
attributes: suit(x) and rank(y)"""
def __init__(self, suit, rank):
"""assigns values to the appropriate attributes
str, str -> str"""
self.x = rank
self.y = suit
def __str__(self):
"""creates a str for appropriate display of cards"""
if not isinstance(self.x,int):
if self.x == "J" or self.x == "j":
x = "Jack"
elif self.x == "Q" or self.x == "q":
x = "Queen"
elif self.x == "K" or self.x == "k":
x = "King"
elif self.x == "A" or self.x == "a":
x = "Ace"
else:
x = str(self.x)
if self.y == "D" or self.x == "d":
y == "Diamonds"
elif self.y == "H" or self.x == "h":
y == "Hearts"
elif self.y == "S" or self.x == "s":
y == "Spades"
elif self.y == "C" or self.x == "c":
y == "Clubs"
return x + " of " + y
def __repr__(self):
"""returns a str that could be used as a command by python"""
return self.x + 'of' + self.y
最佳答案
对于可以用作 Python 表达式的 repr
,它应该返回一个格式为 Card('D', 'J')
的字符串,其中self.suit
和 self.rank
的 repr
分别(为您修正了它们的名称!)到它们的 repr
中代表。
通过使用 %
格式化运算符,这很容易:
def __repr__(self):
return 'Card(%r, %r)' % (self.suit, self.rank)
现在
print(repr(Card('D', 9)))
将输出
Card('D', 9)
<小时/>
在相关说明中,无需测试给定的小写和大写字母的花色和等级,只需在构造函数中将它们转换为大写即可:
if isinstance(rank, str):
self.rank = rank.upper()
else:
self.rank = rank
self.suit = suit.upper()
现在您只需要测试它们的大写变体。尽管我从不建议将 int
和 str
混合以获得这样的值;将卡片编号为 1-13 或 2-14 左右,或者对所有等级使用字符串。
关于python - .__repr__() 帮助 python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29597900/