在python中访问__str__方法中的类属性
我正在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加
card。
或self。
到等级
和suits
:打印:打印:
Add
Card.
orself.
toranks
andsuits
:Prints: