是否可以继续添加具有递增类变量的召回函数?



我在 Python3 中的以下程序中遇到问题,该程序接受一个字符串,其中字符串中的值数量决定了函数在调用时是否再次继续。我被告知,如果我在初始值设定项中使用一个可增量变量,例如 self.turn = 0,我将能够在 move(( 中使用它,而不必在 move(( 中定义它,以免有无限循环。我遇到的问题是,当我运行程序并多次输入"良好输入"(>=3(时,可增量变量 self.turn 保持在 1 而不是像我想要的那样增加。有没有办法在每次调用函数后继续递增? 谢谢 尤

class Player:
def __init__(self):
self.display = 'A'
self.turn = 0 
def move(self, move):
self.move = move
if self.turn == 0 and len(move) <3:
self.turn+=1
print('Your current total of turns: ',self.turn)
print()
exit()

if len(move) >= 3 :
print('good input')
self.turn +=1
print('Your current total of turns: ',self.turn)
print()

else:
print('bad input')
self.turn +=1
print('Your current total of turns: ',self.turn)
print()
exit()
move = input('Input a move: ')
Player().move(move)
move = input('Input a move: ')
Player().move(move)

好的,所以有两件事使你的代码无法正常运行:

  1. 该方法的最后一行代码move是创建类的新对象Player而不是调用同一对象。若要从方法内部从同一对象调用方法,应改用self关键字。
  2. 不应该命名你是一个与变量同名的方法,因为它们的定义会冲突。我改为add_move

此外,您的第一个 if 语句不是必需的,因为该条件已经在下一if中进行了验证,并且else包含基本相同的代码,所以我要删除这部分。

话虽如此,这段代码现在应该可以工作了:

class Player:
def __init__(self):
self.display = 'A'
self.turn = 0
def add_move(self, move):
self.move = move
if len(move) >= 3:
print('good input')
self.turn += 1
print('Your current total of turns: ', self.turn)
print()
else:
print('bad input')
self.turn += 1
print('Your current total of turns: ', self.turn)
print()
exit()
move = input('Input a move: ')
self.add_move(move)  # Now it won't create new objects. Neither colide.

move = input('Input a move: ')
Player().add_move(move)

最新更新