NameError:未定义名称“a”。在同一个类中使用另一个函数的变量

时间:2016-12-01 04:54:00

标签: python

我正在做这个BlackJack程序,当我运行它时,Python告诉我:

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(self)。我想在 init 函数中返回相应的排名值。 例如:如果c2 = PlayingCard(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 个答案:

答案 0 :(得分:0)

无需实例化新课程。将ORIGINAL排名值存储为变量(您应该重命名存储名称值Jack,Queen等的变量。在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