我正在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))
我的程序应该打印Two of Clubs
。
NameError: name 'ranks' is not defined. Did you mean: 'range'?
似乎你不能在Python中以这种方式访问类属性,所以,我如何才能正确地自定义实例的字符串表示?
谢谢!
为ranks
和suits
添加Card.
或self.
:
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