我在下面用构造函数构建了一个类。这个想法是,如果未指定等级和/或花色,则默认情况下应随机生成 PlayingCard 对象。如果指定了无效的花色或等级,则不应创建对象。我相信这是有效的,但我不知道该怎么做。我想验证在无效等级或套装的情况下抛出的唯一异常是我指定的异常。我很困惑为什么会有一个“NameError”说该实例没有属性“suit”,因为我在编写 raise 语句时没有指定这一点。
另外,我想让类变得灵活,以便在创建实例时不需要将用户定义的等级和西装作为字符串传递,但我似乎无法让它工作。如果有人能指出我正确的方向或解释我为什么不想这样做,将不胜感激。
class PlayingCard:
ranks = ['2','3','4','5','6','7','8','9','10','J','Q','K','A']
suits = ['Spades', 'Hearts', 'Clubs', 'Diamonds']
def __init__(self, rank = None, suit = None):
if rank is None: self.rank = PlayingCard.ranks[rand.randint(0,12)]
elif rank in PlayingCard.ranks: self.rank = rank
if suit is None: self.suit = PlayingCard.suits[rand.randint(0,3)]
elif suit in PlayingCard.suits: self.suit = suit
if self.rank not in PlayingCard.ranks or self.suit not in PlayingCard.suits: raise NameError('Invalid Suit or Rank')
>>> c1 = PlayingCard('15','Diamonds')
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
c1 = PlayingCard('15','Diamonds')
File "C:\Python27\poker.py", line 26, in __init__
if self.rank not in PlayingCard.ranks or self.suit not in PlayingCard.suits: raise NameError('Invalid Suit or Rank')
AttributeError: PlayingCard instance has no attribute 'rank'
>>> c2 = PlayingCard('A', 'Swords')
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
c2 = PlayingCard('A', 'Swords')
File "C:\Python27\poker.py", line 26, in __init__
if self.rank not in PlayingCard.ranks or self.suit not in PlayingCard.suits: raise NameError('Invalid Suit or Rank')
AttributeError: PlayingCard instance has no attribute 'suit'