如何从函数中永久地更改python中的全局变量?

时间:2018-05-29 12:41:43

标签: python

我试图在python中创建一个基于文本的冒险游戏,其中将与怪物和商店进行战斗,您可以在其中增加您的健康和伤害。我意识到在功能中使用全局变量是不可取的,但我还没有找到另一种方法来实现我想要做的事情。战斗和商店出现在游戏的多个点,所以我认为定义它们将是反复使用它们的最佳方式。这是一个小部分,指的是商店中的商品:

import random

own_health = 15
gold = 10
helmet = False

def helmet():
    global own_health
    global gold
    global helmet
    health_boost = random.randint(2,5)
    cost = random.randint(7,10)
    print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
    buy = input("Would you like to buy and equip the helmet? (y/n): ")
    if buy == "y":
        if gold - cost > -1 and helmet == False:
            gold -= cost
            own_health += health_boost
            helmet = True
        elif gold - cost < 0:
            print("You don't have enough money to buy this helmet.")
        elif helmet == True:
            print("You are already wearing a helmet.")
    elif buy == "n":
        print("You didn't buy the helmet.")
    else:
        print("Invalid input.")

helmet()
print(own_health)
print(gold)
print(helmet)

此代码的结果是own_health,gold和helmet被设置回执行函数helmet()之前的原始值。有没有办法解决这个问题,以便在执行功能后永久设置全局变量?如果没有,我渴望听到任何不同的方式来编写程序。

4 个答案:

答案 0 :(得分:4)

JsonSerializationException

这种情况永远不会成功,因为if gold - cost > -1 and helmet == False: 在函数内永远不会为假。当您定义具有相同名称的函数时,您在helmethelmet下面创建的own_health会被覆盖。尝试为您的函数指定一个不同的名称,例如gold。那么你的全局变量应该根据需要更新:

get_helmet

答案 1 :(得分:0)

确实应该避免全局变量。将它们作为参数传递将是首选。

您有多个相同变量的实例。您的全局变量不应在函数内声明,而应在外部声明。如果全局变量在声明它们的文件之外使用,则导入该文件并将文件名附加到全局变量的开头。

import fileName

fileName.gold ...

答案 2 :(得分:0)

我会创建一个类:

import random

class myClass:

    def __init__(self, own_health, gold, helmet):
        self.own_health = own_health
        self.gold = gold
        self.helmet = helmet

    def buyHelmet(self):
        health_boost = random.randint(2,5)
        cost = random.randint(7,10)
        print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
        buy = input("Would you like to buy and equip the helmet? (y/n): ")
        if buy == "y":
            if self.gold - cost > -1 and self.helmet == False:
                self.gold -= cost
                self.own_health += health_boost
                self.helmet = True
            elif self.gold - cost < 0:
                print("You don't have enough money to buy this helmet.")
            elif self.helmet == True:
                print("You are already wearing a helmet.")
        elif buy == "n":
            print("You didn't buy the helmet.")
        else:
            print("Invalid input.")

kbball = myClass(15, 10, False)

print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)

kbball.buyHelmet()

print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)

#output

15
10
False
There is a helmet that costs 10 and will increase your health by 2
17
0
True

答案 3 :(得分:0)

解决此问题的一种方法是使用OOP。

class Game():
    def __init__(self):
        self.own_health = 15
        self.gold = 10
        self.helmet = 5

    def helmet(self):
        health_boost = random.randint(2,5)
        cost = random.randint(7,10)
        print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
        buy = input("Would you like to buy and equip the helmet? (y/n): ")
        if buy == "y":
            if self.gold - cost > -1 and self.helmet == False:
                self.gold -= cost
                self.own_health += health_boost
                self.helmet = True
            elif self.gold - cost < 0:
                print("You don't have enough money to buy this helmet.")
            elif self.helmet == True:
                print("You are already wearing a helmet.")
        elif buy == "n":
            print("You didn't buy the helmet.")
        else:
            print("Invalid input.")

然后定义一些函数,返回全局变量的值。

   def get_own_health(self):
       return self.own_health

现在您可以按如下方式检查变量值:

game = Game() 
game.helmet()
print(game.get_own_health())