简体   繁体   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()

So basically I'm working on a simple game for myself on Python, and I'm having an issue with my variables as when I run the program original variables are set to 50 dmg and 100 health, but what I want to do is be able to run the code, change the variables and then have them stay as that. 因此,基本上我正在为自己开发一个使用Python的简单游戏,并且我的变量存在问题,因为当我运行程序时,原始变量设置为50 dmg和100健康,但是我想做的是能够运行代码,更改变量,然后按原样保留它们。 Although I understand why the variables aren't staying as the new values, I have no clue how to over-write them, help would be much appreciated. 尽管我理解了为什么变量没有保留为新值的原因,但是我不知道如何覆盖它们,所以不胜感激。

Thanks. 谢谢。

I suggest creating a class to package all of the variables into a single object: 我建议创建一个类以将所有变量打包到一个对象中:

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

Now you create an instance of the class: 现在,您创建该类的实例:

player = player_character()

And change the variables directly: 并直接更改变量:

player.health -= 10

Alternatively, you can add functions to the class: 另外,您可以向类添加函数:

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

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

Now you can call the function on an object: 现在,您可以在对象上调用该函数:

player.hit(10)

Classes are incredibly powerful and great tools for organizing code. 类是组织代码的强大工具。 They allow you to treat a lot of data as a single entity. 它们使您可以将大量数据视为一个实体。 I strongly encourage you to learn more about them and object oriented programming in general. 我强烈建议您进一步了解它们以及一般的面向对象编程。

Place the variables outside function body and make them accessible within usng global keyword: 将变量放置在函数体外部,并在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