在python中访问__str__方法中的类属性

发布于 2025-02-05 04:35:20 字数 741 浏览 1 评论 0原文

我正在python 3.x上做一个纸牌课程。我正在尝试利用__ str __方法打印卡。

class Card:

    ranks = ["Ace", "Two", "Three", "Four", "Five", "Six",
             "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]

    def __init__(self, rank=-1, suit=-1):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        if self.rank != -1 and self.suit != -1:
            return "{0} of {1}".format(ranks[self.rank], suits[self.suit])
        else:
            return "Null"

print(Card(1, 0))

我的程序应打印<代码>俱乐部的两个。

相反,我收到:name error:name'等级'未定义。您的意思是:“范围”?

看来您无法以这种方式访问​​类属性,因此,我如何正确自定义实例的字符串表示形式?

谢谢!

I am making a card class in Python 3.x. I am trying to utilize the __str__ method to print the card.

class Card:

    ranks = ["Ace", "Two", "Three", "Four", "Five", "Six",
             "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]

    def __init__(self, rank=-1, suit=-1):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        if self.rank != -1 and self.suit != -1:
            return "{0} of {1}".format(ranks[self.rank], suits[self.suit])
        else:
            return "Null"

print(Card(1, 0))

My program should print Two of Clubs.

Instead, I receive: NameError: name 'ranks' is not defined. Did you mean: 'range'?

It seems you cannot access class attributes this way in Python, so, how can I properly customize the string representation of my instances?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不是你的备胎 2025-02-12 04:35:20

添加card。self。等级suits

class Card:

    ranks = ["Ace", "Two", "Three", "Four", "Five", "Six",
             "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]

    def __init__(self, rank=-1, suit=-1):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        if self.rank != -1 and self.suit != -1:
            return "{0} of {1}".format(Card.ranks[self.rank], Card.suits[self.suit])
        else:
            return "Null"

print(Card(1, 0))

打印:打印:

Two of Clubs

Add Card. or self. to ranks and suits:

class Card:

    ranks = ["Ace", "Two", "Three", "Four", "Five", "Six",
             "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]

    def __init__(self, rank=-1, suit=-1):
        self.rank = rank
        self.suit = suit

    def __str__(self):
        if self.rank != -1 and self.suit != -1:
            return "{0} of {1}".format(Card.ranks[self.rank], Card.suits[self.suit])
        else:
            return "Null"

print(Card(1, 0))

Prints:

Two of Clubs
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文