PYTHON: AttributeError: 'int' object has no attribute 'hand'

PYTHON: AttributeError: 'int' object has no attribute 'hand'

所以我有一个关于 python 的练习 - 构建 BlackJack 游戏。 我已经开始定义游戏的每个短语将如何进行。 现在,当我 运行 下面的代码时,如果输入为“0”——这意味着您不再需要卡片,它 运行 就完美了。但是当输入为“1”时——这意味着你想选择卡片,我得到一个错误:

Traceback (most recent call last):
  File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 1, in <module>
    class blackjack(object):
  File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 34, in blackjack
    player(1)
  File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 25, in player
    PickCard(1)
  File "C:/Users/Maymon/PycharmProjects/untitled4/BlackJack.py", line 18, in PickCard
    self.hand+= random.randrange(1, 13)
AttributeError: 'int' object has no attribute 'hand'

代码:

class blackjack(object):

    #this func defines how player should react
    def player(self):

        #this func defines what case of technical loosing
        def loser():
            print("You have reached", hand , ". Which is beyond 21. Therefor, you have lost the game. Better luck next time!")


        #this func is responsible for picking card issue.
        def PickCard(self):
            import random
            x=1
            while x == 1:
                pick = int(raw_input("Enter 1 if you want another card, else Enter 0"))
                if pick == 1:
                    self.hand = self.hand + random.randrange(1, 13)
                else:
                    x=0
        import random
        print "Now your first card will automatically be given to you:"
        hand=random.randrange(1,13)
        print "hand: ", hand
        PickCard(1)
        print hand
        if hand>21:
            loser()
        elif hand==21:
            pass
        else:
            pass

    player(1)

提前致谢。

您正在将函数调用作为 player(1),其中 player 函数期望参数为 self 类型。即class blackjack 的实例。因此,在执行 self.hand = self.hand + random.randrange(1, 13) 时会抛出上述错误。


我认为您不想从 class 中调用 player() 函数,是吗?将该部分移到 class 之外。首先创建 class blackjack 的对象(注意:在 Python 中, class 名称应定义为 CamelCase 变量,如:BlackJack)。例如:

blackjack_obj = blackjack()

然后调用player()函数为:

blackjack_obj.player()