Python范围、字典和变量的区别?

Python范围、字典和变量的区别?,python,dictionary,scope,Python,Dictionary,Scope,我有同样的问题,但略有不同 number = 0 def incrementNumber(): number += 1 上面的这个不行,但下面的这个不行,为什么?两者都在功能范围之外 number = {'num':0} def incrementNumber(): number['num'] += 1 如果我将变量添加为全局变量,则第一个变量有效 number = 0 def incrementNumber(): global number number +

我有同样的问题,但略有不同

number = 0
def incrementNumber():
    number += 1
上面的这个不行,但下面的这个不行,为什么?两者都在功能范围之外

number = {'num':0}
def incrementNumber():
    number['num'] += 1
如果我将变量添加为全局变量,则第一个变量有效

number = 0
def incrementNumber():
    global number
    number += 1
看看这个,它和你正在做的很相似。特别是亚当的评论

您没有分配给dictionaryVar,而是分配给dictionaryVar['A']。 所以它从未被分配到,所以它是隐式全局的。如果你 如果实际分配给dictionaryVar,您将得到您想要的行为 我们“期待”


在第一种情况下,
int
是不可变的,因此当您执行
number+=1
时,您实际上在更新
number
点的位置。通常情况下,您不希望更改传播到上一个作用域,而不传播到下一个作用域 python显式地告诉它,它会在写入时进行复制,并给您一个局部变量号。您可以增加该变量,然后在函数返回时将其丢弃

在字典的情况下,它是可变的,您将获取上作用域引用,然后对底层对象进行变异,因此添加的内容将传播到函数之外

在上一个例子中,您明确地告诉python不要将number设置为局部变量,因此更改会按您的需要传播出去

相关的

第二句中的“it's”指的是什么,dictionaryVar还是dictionaryVar['A']?看起来像是dictionaryVar['A'],那么“adam”是不是说dictionaryVar['A']是隐式全局的?为什么会这样呢。我希望,像博主一样,dictionaryVar['A']不会隐式地全球化,如果dictionaryVar不是。。。你能在回答中再解释一下吗?