.repr()帮助python 3
我正在为扑克牌创建一个类定义。一张扑克牌需要存储有关其套装(梅花、钻石、红桃或黑桃)和等级(2-10、杰克、女王、国王或王牌)的信息。我的下一步,即创建.repr()帮助python 3,python,python-3.x,Python,Python 3.x,我正在为扑克牌创建一个类定义。一张扑克牌需要存储有关其套装(梅花、钻石、红桃或黑桃)和等级(2-10、杰克、女王、国王或王牌)的信息。我的下一步,即创建。\uuu repr\uuu()方法,给我带来了麻烦。我知道它将类似于我的。\uuuu str\uuuu方法,但\uuu repr\uuuu方法仍然给我带来麻烦。这就是我到目前为止所做的: class Card: """a class for determining suit and rank of a card in a 52-card dec
。\uuu repr\uuu()
方法,给我带来了麻烦。我知道它将类似于我的。\uuuu str\uuuu
方法,但\uuu repr\uuuu
方法仍然给我带来麻烦。这就是我到目前为止所做的:
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)
现在
将输出
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左右,也可以对所有等级使用字符串。是否有特定的原因让您重新定义str和repr,而不只是按照说明使用卡片组和卡片类@Jgreenwell\uuuuu repr\uuuuu
没有问题,只要有更简单的方法,当选项存在时:)不确定\uuuuuuu repr\uuuu
会给你带来什么麻烦。按照说明使用合适的实例属性名称怎么样,self.rank
和self.suit
比x
和y
更易读
if isinstance(rank, str):
self.rank = rank.upper()
else:
self.rank = rank
self.suit = suit.upper()