简体   繁体   English

全局范围变量在python中保持不变

[英]Global scope variable unchanging in python

In this code 在这段代码中

 money = .3 Things = ["Nothing"] def main(): print "go to buy things" print "Current Money %s" % (money) print "Things you have:" for item in Things: print item wait = raw_input() buythings(money) def buythings(money): print "Type Buy to buy things" buy = raw_input() if buy == "buy": money = money - .3 Things.append("Things") main() else: print "you bought nothing" print "" main() 

Why after buying the things does the money not go down? 为什么买东西后钱不下来? This has been a problem to me for a while now and I cant seem to understand how the scope works in this situation. 这对我来说已经有一段时间了,我似乎无法理解示波器在这种情况下是如何工作的。

The global variable money is shadowed by the function parameter money in buythings(money) function. 全局变量moneybuythings(money)函数中的函数参数money buythings(money) You should remove the parameter for it to work: 您应该删除该参数才能使其正常工作:

def main():
    global money
    global Things
    ...

def buythings():
    global money
    global Things
    ...

However, A better approach, as alfasin pointed out, would be passing money and Things as parameters to both functions and not using global keyword at all: 但是,如alfasin所指出的,更好的方法是将moneyThings作为参数传递给两个函数,而完全不使用global关键字:

def main(money, things):
    ...
    for item in things:
        print item
    wait = raw_input()
    buythings(money, things)


def buythings(money, things):
    ...
    if buy == "buy":
        money = money - .3
        Things.append("Things")
        main(money, things)
    else:
        ...
        main(money, things)

>>> money = .3
>>> Things = ["Nothing"]
>>> main(money, Things)

Hope this helps. 希望这可以帮助。

You can use a global variable in other functions by declaring it as global in each function that assigns to it: 通过在分配给每个函数的每个函数中将其声明为全局变量,可以在其他函数中使用全局变量:

money = 0

def set_money_to_one():
    global money    # Needed to modify global copy of money
    money = 1

def print_money():
    print money     # No need for global declaration to read value of money

set_money_to_one()
print_money()       # Prints 1

In your case : 在您的情况下:

def buythings():
    global money

Python wants to make sure that you really know what you're playing with by explicitly requiring the global keyword. Python希望通过显式要求global关键字来确保您真正了解自己在玩什么。

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

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