2016-12-01 48 views
-3

裏面我做這個節目的BlackJack另一個函數變量,當我跑了,Python的告訴我這一點:NameError:名稱'a'未定義。使用同一類

Traceback (most recent call last): 
    File "<pyshell#17>", line 1, in <module> 
    c2.bj_value() 
    File "/Users/xuanruizhang/Desktop/lab_class_design.py", line 47, in bj_value 
    s = PlayingCard(a,b) 
NameError: name 'a' is not defined 

所以問題是與功能bj_value(個體經營)。我想返回init函數中相應的排名值。 例如:如果C2 =遊戲牌(11, 「C」),然後c2.bj_value()應返回10

class PlayingCard: 
    def __init__(self, rank, suit): 
     if rank == 1: 
      self.rank = "Ace" 
     elif rank == (2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10): 
      self.rank = rank 
     elif rank == 11: 
      self.rank = "Jack" 
     elif rank == 12: 
      self.rank = "Queen" 
     elif rank == 13: 
      self.rank = "King" 
     if suit == "h": 
      self.suit = "Hearts" 
     elif suit == "s": 
      self.suit = "Spades" 
     elif suit == "c": 
      self.suit = "Clubs" 
     elif suit == "d": 
      self.suit = "Diamonds" 

    def get_rank(self): 
     if self.rank == (2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10): 
      return self.rank 
     elif self.rank == "Ace": 
      return 1 
     elif self.rank == "Jack": 
      return 11 
     elif self.rank == "Queen": 
      return 12 
     elif self.rank == "King": 
      return 13 


    def get_suit(self): 
     if self.suit == "Hearts": 
      return "h" 
     elif self.suit == "Jack": 
      return "j" 
     elif self.suit == "Clubs": 
      return "c" 
     elif self.suit == "Diamonds": 
      return "d" 


    def bj_value(self): 
     s = PlayingCard(a, b) 
     if s.a == 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 10: 
      return s.a 
     elif s.a == 11 or 12 or 13: 
      return 10 



    def __repr__(self): 
     return '%s of %s' % (self.rank, self.suit) 

    def main(): 

     if __name__ == '__main__': 
      main() 

謝謝!

+1

不相關的問題,但'等級== (2或3或4或5或6或7或8或9或10)'不會做你認爲它的做法 – wim

+0

@wim建議,你應該做一些事情,如'如果在範圍內排名(2,11) ' –

+0

您可能需要審查類和範圍的教程。 – TigerhawkT3

回答

0

無需實例化一個新的類。存儲原始等級值作爲變量(你應該重命名變量存儲名稱值的傑克,女王,bj_value函數內等訪問self.rank:

class PlayingCard: 
    def __init__(self, rank, suit): 
     self.rank = rank 

     if rank == 1: 
      self.card = "Ace" 
     elif rank in range(2, 11): 
      self.card = str(rank) 
     elif rank == 11: 
      self.card = "Jack" 
     elif rank == 12: 
      self.card = "Queen" 
     elif rank == 13: 
      self.card = "King" 
     if suit == "h": 
      self.suit = "Hearts" 
     elif suit == "s": 
      self.suit = "Spades" 
     elif suit == "c": 
      self.suit = "Clubs" 
     elif suit == "d": 
      self.suit = "Diamonds" 

.... 

    def bj_value(self): 
     if self.rank in range(1,11): 
      return self.rank 
     elif self.rank in range(11,14): 
      return 10 
+0

明白了!但是,你能告訴我,爲什麼這個作品?太謝謝你了! – xzhang66

+0

所以你最初的錯誤是從錯誤信息自明。您使用的變量在任何地方都沒有定義。如果你只是存儲原始的rank值,get_rank是完全多餘的e __init__。然後,您可以在該類中定義的其他方法中訪問該存儲的值。 https://docs.python.org/2/tutorial/classes.html – aikramer2

+0

太謝謝你了! – xzhang66