【问题标题】:Global scope variable unchanging in pythonpython中的全局范围变量不变
【发布时间】:2015-02-23 06:33:01
【问题描述】:

在这段代码中

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()

为什么买东西后钱不下来?这对我来说已经有一段时间了,我似乎无法理解示波器在这种情况下是如何工作的。

【问题讨论】:

    标签: python variables scope


    【解决方案1】:

    全局变量moneybuythings(money)函数中的函数参数money遮蔽。您应该删除该参数以使其工作:

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

    但是,正如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)
    

    希望这会有所帮助。

    【讨论】:

    • 正确,但这还不够,main() 也应该将 money 声明为全局变量(但全局变量是邪恶的——对吗?),或者更好的是,buythings() 应该返回更新后的变量moneymain()
    【解决方案2】:

    您可以在其他函数中使用全局变量,方法是在分配给它的每个函数中将其声明为全局变量:

    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
    

    在你的情况下:

    def buythings():
        global money
    

    Python 想要确保你真的知道你是什么 通过明确要求全局关键字来玩。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-13
      • 2013-05-26
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2015-08-07
      相关资源
      最近更新 更多