【问题标题】:Python scope, dictionary and variables difference?Python范围,字典和变量的区别?
【发布时间】:2012-10-15 03:58:13
【问题描述】:

Python scope 我有同样的问题,但略有不同。

number = 0
def incrementNumber():
    number += 1

上面这个不行,下面这个不行,为什么?两者都在函数范围之外。

number = {'num':0}
def incrementNumber():
    number['num'] += 1

如果我将变量添加为全局变量,则第一个有效

number = 0
def incrementNumber():
    global number
    number += 1

【问题讨论】:

    标签: python dictionary scope


    【解决方案1】:

    看看这个blog post,它和你正在做的类似。特别是亚当的评论。

    您没有分配给dictionaryVar,而是分配给dictionaryVar['A']。 所以它永远不会被分配给它,所以它是隐式的全局的。如果你 要实际分配给dictionaryVar,你会得到你的行为 “期待”。

    【讨论】:

    • 第二句中的“it's”是什么意思,dictionaryVar 还是dictionaryVar['A']?看起来像dictionaryVar['A'],那么“adam”是否说dictionaryVar['A'] 是隐式全局的?为什么会这样。我希望,像博主一样,如果 dictionaryVar 不是,dictionaryVar['A'] 不会是隐式全局的......你能在你的答案中解释更多吗?
    【解决方案2】:

    在第一种情况下,int 是不可变的,因此当您执行number +=1 时,您实际上是在更新number 指向的位置。因为您通常不希望更改在没有超出范围的情况下传播 明确告诉它,python 会进行写时复制并为您提供局部变量编号。您比增加该变量并在函数返回时将其丢弃

    对于可变的字典,您正在获取向上范围的引用,然后改变底层对象,因此您的添加会传播到函数之外。

    在最后一种情况下,您已明确告诉 python 将 number 设为局部变量,因此更改会根据需要传播出去。

    相关python closure local variables

    【讨论】:

      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 2017-12-08
      • 2015-10-13
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      相关资源
      最近更新 更多