类和例外

时间:2012-12-26 18:59:47

标签: python class exception raise

我在下面用构造函数构建了一个类。这个想法是,如果没有指定等级和/或套装,默认情况下应该随机生成一个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'

1 个答案:

答案 0 :(得分:6)

如果rank不是None而且ranks中没有,self.rank永远不会设置,那么

if self.rank not in PlayingCard.ranks

不起作用; self.rank不存在。同样适用于suit。您可以更具体地处理错误并立即解决问题:

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
    else: raise NameError('Invalid rank')

    if suit is None: self.suit = PlayingCard.suits[rand.randint(0,3)]
    elif suit in PlayingCard.suits: self.suit = suit
    else: raise NameError('Invalid suit')