繁体   English   中英

如何在函数中覆盖python中的变量

[英]How to overwrite variable in python in a function

def Change_char_stats():
    Char_dmg = 50
    Char_health = 100
    Char_stat_choice= ''
    print('Current Damage is:',Char_dmg,'and health is:',Char_health,'.')
    Char_stat_choice=input('\nWhat character stat would you like to edit?')

    if Char_stat_choice == '1':
        print('Current damage is',Char_dmg,'.')
        Char_dmg=int(input('Character damage to: '))
        print('Character damage has been changed to',Char_dmg,'.')
        Change_char_stats()

    elif Char_stat_choice == '2':
        print('Current damage is',Char_health,'.')
        Char_health=int(input('Character health to: '))
        print('Character health has been changed to',Char_health,'.')
        Change_char_stats()
    else:
        print('Input invalid.')
        Change_char_stats()

Change_char_stats()

因此,基本上我正在为自己开发一个使用Python的简单游戏,并且我的变量存在问题,因为当我运行程序时,原始变量设置为50 dmg和100健康,但是我想做的是能够运行代码,更改变量,然后按原样保留它们。 尽管我理解了为什么变量没有保留为新值的原因,但是我不知道如何覆盖它们,所以不胜感激。

谢谢。

我建议创建一个类以将所有变量打包到一个对象中:

def class player_character:
    def __init__(self):
        self.health = 100
        self.dmg = 50

现在,您创建该类的实例:

player = player_character()

并直接更改变量:

player.health -= 10

另外,您可以向类添加函数:

def class player_character:
    def __init__(self):
        self.health = 100
        self.dmg = 50

    def hit(self, dmg):
        self.health -= dmg

现在,您可以在对象上调用该函数:

player.hit(10)

类是组织代码的强大工具。 它们使您可以将大量数据视为一个实体。 我强烈建议您进一步了解它们以及一般的面向对象编程。

将变量放置在函数体外部,并在usng全局关键字中访问它们:

somevar = 5

def foobar(x):
    global somevar
    somevar = x

print somevar
foobar(6)
print somevar

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM