python - .__repr__() 帮助 python 3

标签 python python-3.x

我正在为扑克牌创建一个类定义。扑克牌需要存储有关其花色(梅花、方 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.suitself.rankrepr 分别(为您修正了它们的名称!)到它们的 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()

现在您只需要测试它们的大写变体。尽管我从不建议将 intstr 混合以获得这样的值;将卡片编号为 1-13 或 2-14 左右,或者对所有等级使用字符串。

关于python - .__repr__() 帮助 python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29597900/

相关文章:

python-3.x - 在 python 中删除 AWS Lambda 函数上的触发器

python : printing lines of factorial "*" through recursion

python - 如何使用 python 和 mysqldb 创建动态 sql 语句

python - 如何将 Django .html 指向 S3 媒体文件?拒绝访问

python - 具有一组常量属性的 Init 类实例,这些实例被初始化一次

python - 解包、扩展解包和嵌套扩展解包

Python读取LTspice图导出

python - Shodan.py 搜索在打印匹配列表时不打印完整的结果集

python - 用于显示/隐藏/切换选项卡的 Sublime Text 2/3 快捷方式

python - Tkinter - 如何停止在 Canvas 窗口上方滚动