全球字典不需要关键字全局来修改它们? [英] Global dictionaries don't need keyword global to modify them?

查看:130
本文介绍了全球字典不需要关键字全局来修改它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我想知道为什么我可以在没有全局关键字的情况下更改全局字典?为什么其他类型是强制性的?这背后有什么逻辑吗?



例如。代码:

 #!/ usr / bin / env python3 

stringvar =mod
dictvar = {'key1':1,
'key2':2}

def foo():
dictvar ['key1'] + = 1

def bar():
stringvar =bar
print(stringvar)

print(dictvar)
foo()
print(dictvar)

print(stringvar)
bar()
print(stringvar)

提供以下结果:

  me @ pc:〜/ $ ./globalDict.py 
{'key2':2,'key1':1}
{'key2':2,'key1':2}#字典值已更改
mod
bar
mod

我期望的是:

  me @ pc:〜/ $ ./globalDict.py 
{'key2':2,'key1':1}
{'key2' :2,'key1':1}#我没有使用全局,所以字典保持不变
mod
bar
mod
pre>

解决方案

原因是e线

  stringvar =bar

是不明确的,它可能是指一个全局变量,它可能会创建一个新的局部变量,名为 stringvar 。在这种情况下,Python默认假定它是一个局部变量,除非已经使用了全局关键字。



但是,行

  dictvar ['key1'] + = 1 
pre>

完全是明确的。它可以仅指全局变量 dictvar ,因为 dictvar 必须已经存在,因为该语句不会引发错误



这不是特定于字典 - 列表也是如此:

  listvar = [hello,world] 

def listfoo():
listvar [0] =再见

或其他类型的对象:

  MyClass:
foo = 1
myclassvar = MyClass()

def myclassfoo():
myclassvar.foo = 2

只要使用变异操作而不是重新绑定操作


Possible Duplicate:
Why is not the keyword global not required in this case?

I wonder why I can change global dictionary without global keyword? Why it's mandatory for other types? Is there any logic behind this?

E.g. code:

#!/usr/bin/env python3

stringvar = "mod"
dictvar = {'key1': 1,
           'key2': 2}

def foo():
    dictvar['key1'] += 1

def bar():
    stringvar = "bar"
    print(stringvar)

print(dictvar)
foo()
print(dictvar)

print(stringvar)
bar()
print(stringvar)

Gives following results:

me@pc:~/$ ./globalDict.py 
{'key2': 2, 'key1': 1}
{'key2': 2, 'key1': 2}  # Dictionary value has been changed
mod
bar
mod

where I would expect:

me@pc:~/$ ./globalDict.py 
{'key2': 2, 'key1': 1}
{'key2': 2, 'key1': 1}  # I didn't use global, so dictionary remains the same
mod
bar
mod

解决方案

The reason is that the line

stringvar = "bar"

is ambiguous, it could be referring to a global variable, or it could be creating a new local variable called stringvar. In this case, Python defaults to assuming it is a local variable unless the global keyword has already been used.

However, the line

dictvar['key1'] += 1

Is entirely unambiguous. It can be referring only to the global variable dictvar, since dictvar must already exist for the statement not to throw an error.

This is not specific to dictionaries- the same is true for lists:

listvar = ["hello", "world"]

def listfoo():
    listvar[0] = "goodbye"

or other kinds of objects:

class MyClass:
    foo = 1
myclassvar = MyClass()

def myclassfoo():
    myclassvar.foo = 2

It's true whenever a mutating operation is used rather than a rebinding one.

这篇关于全球字典不需要关键字全局来修改它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆