我如何摆脱 Python 中的全局变量?
Posted
技术标签:
【中文标题】我如何摆脱 Python 中的全局变量?【英文标题】:How might I move away from globals in Python? 【发布时间】:2022-01-21 15:02:13 【问题描述】:在此示例中,如果我将注释代码换出,global
变量将正常工作。我似乎无法在这里了解有关 Python 的一些基本知识,因为传递变量似乎无法正常工作。
import random
def roll_die(sides=6):
return random.randint(1, sides)
# def game():
def game(score_p1,score_p2,rounds):
# global score_p1
# global score_p2
# global rounds
roll_1=roll_die()
roll_2=roll_die()
winner=None
if roll_1 > roll_2:
score_p1 = score_p1 +1
score_p2 = score_p2 -1
winner='player 1'
if roll_1 < roll_2:
score_p1 = score_p1 -1
score_p2 = score_p2 +1
winner='player 2'
if roll_1 == roll_2:
winner='No one'
print(f'p1 rolled roll_1 and p2 rolled roll_2: Winner is winner ')
print(score_p1,score_p2)
rounds = rounds + 1
# print(score_p1,score_p2, rounds)
return score_p1,score_p2,rounds
if __name__ == '__main__':
tokens=5
score_p1=tokens
score_p2=tokens
rounds=0
while True:
if (score_p1 <= 0) or (score_p2 <= 0):
print(f'Final Score: score_p1:score_p2 with rounds rounds')
break
else:
# game()
game(score_p1,score_p2,rounds)
我从 非全局 版本获得的示例结果:
p1 rolled 3 and p2 rolled 1: Winner is Player 1
6 4
p1 rolled 1 and p2 rolled 4: Winner is Player 2
4 6
p1 rolled 5 and p2 rolled 3: Winner is Player 1
6 4
p1 rolled 3 and p2 rolled 1: Winner is Player 1
6 4
p1 rolled 4 and p2 rolled 4: Winner is No one
5 5
p1 rolled 2 and p2 rolled 2: Winner is No one
5 5
...游戏永远循环
【问题讨论】:
【参考方案1】:您必须将game
返回的值重新分配给名称:
while True:
if (score_p1 <= 0) or (score_p2 <= 0):
print(f'Final Score: score_p1:score_p2 with rounds rounds')
break
else:
score_p1, score_p2, rounds = game(score_p1,score_p2,rounds)
【讨论】:
【参考方案2】:一种解决方案是将这些变量存储在一个对象中,以便它们在函数调用之间持续存在——例如,您的所有游戏状态都可以存在于 Game
对象中,如下所示:
import random
def roll_die(sides=6):
return random.randint(1, sides)
class Game:
def __init__(self):
self.tokens = self.score_p1 = self.score_p2 = 5
self.rounds = 0
def play(self):
roll_1 = roll_die()
roll_2 = roll_die()
if roll_1 > roll_2:
self.score_p1 += 1
self.score_p2 -= 1
winner = 'player 1'
elif roll_1 < roll_2:
self.score_p1 -= 1
self.score_p2 += 1
winner = 'player 2'
else:
winner = 'No one'
print(f'p1 rolled roll_1 and p2 rolled roll_2: Winner is winner ')
print(self.score_p1, self.score_p2)
self.rounds += 1
if __name__ == '__main__':
game = Game()
while True:
game.play()
if game.score_p1 <= 0 or game.score_p2 <= 0:
print(f'Final Score: game.score_p1:game.score_p2 with game.rounds rounds')
break
【讨论】:
这些答案显示了针对一个问题的两种截然不同的解决方案。一个是对原始问题的直接解决方案,另一个是使用类显示“更好”答案的解决方案。总之,这些答案还有助于向初学者展示使用非常简单有趣的程序进行类编码可能更适合的地方。以上是关于我如何摆脱 Python 中的全局变量?的主要内容,如果未能解决你的问题,请参考以下文章