【问题标题】:Is an incremented variable able to be used again in a function call in Python是否可以在 Python 的函数调用中再次使用自增变量
【发布时间】:2020-05-13 11:16:48
【问题描述】:

所以,我正在开发一款需要用户输入才能移动的游戏。我使用一个变量来计算函数内的转数。我遇到的问题是,只要不满足某些条件(x!= y),我就想调用该函数,因此用户可以输入另一个输入。问题是因为我在函数 (turn) 中使用了变量,当我调用该函数时,它会重置为 1 并因此陷入无限循环。

在这种情况下,有没有办法使用变量 (turn) 并在每增加一个回合时保持其总数?

非常感谢,谢谢!

PS。我是 Python 新手

class Player:
    def __init__(self):
        self.display = 'A'
        
    def move(self, move):
        self.move = move
        turn = 1
        while x != y:
          if self.move == 's':
            print('correct')
            turn +=1
        change = input('Input a move: ')
        Player().move(change)
            
change = input('Input a move: ')
Player().move(change)

【问题讨论】:

    标签: python function class variables


    【解决方案1】:

    这就是对象数据成员的用途。将turn 转换为这样的数据成员:

    class Player:
        def __init__(self):
            self.display = 'A'
            self.turn = 1      # initialize in constructor instead of in 'move'
    
        def move(self, move):
            self.move = move
            while x != y:
              if self.move == 's':
                print('correct')
                self.turn +=1  # Access as a data member
            change = input('Input a move: ')
            Player().move(change)
    

    现在,self.turn 将在调用 move 之间保留。

    【讨论】:

      【解决方案2】:

      您可以将turn 设为 Player 类中的一个字段,并在 init 中将其设置为 1。这样,在 Player 对象上多次调用 move() 时,它不会重置为 1。

      【讨论】:

        猜你喜欢
        • 2021-08-06
        • 2016-03-30
        • 2019-11-21
        • 2013-07-16
        • 2010-09-08
        • 2015-10-06
        • 1970-01-01
        • 2023-02-08
        • 1970-01-01
        相关资源
        最近更新 更多