使用“全球” Python中的关键字 [英] Use of "global" keyword in Python

查看:101
本文介绍了使用“全球” Python中的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过阅读文档了解到,Python对函数有一个单独的命名空间,如果我想在该函数中使用全局变量,我需要使用 global

What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use global.

我使用的是Python 2.7,我试过这个小测试

I'm using Python 2.7 and I tried this little test

>>> sub = ['0', '0', '0', '0']
>>> def getJoin():
...     return '.'.join(sub)
...
>>> getJoin()
'0.0.0.0'

即使没有全球。我能够访问全局变量没有任何问题。

It seems things are working fine even without global. I was able to access global variable without any problem.

我错过了什么吗?另外,以下是来自Python文档的内容:

Am I missing anything? Also, following is from Python documentation:


全局语句中列出的名称
不能定义为正式
参数或for循环控制
target,类定义,函数
定义或导入语句。

Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

虽然形式参数和类定义对我来说是有意义的,但是我无法理解对循环控制目标和函数定义的限制。

While formal parameters and class definition make sense to me, I'm not able to understand the restriction on for loop control target and function definition.

推荐答案

关键字 global 仅用于在本地环境中更改或创建全局变量,尽管创建全局变量很少被认为是一个好的解决方案。

The keyword global is only useful to change or create global variables in a local context, although creating global variables is seldom considered a good solution.

def bob():
    me = "locally defined"    # Defined only in local context
    print me

bob()
print me     # Asking for a global variable

以上会给你:

The above will give you:

locally defined
Traceback (most recent call last):
  File "file.py", line 9, in <module>
    print me
NameError: name 'me' is not defined

您使用全局语句,该变量将变得可用于该函数范围之外,实际上成为全局变量。

While if you use the global statement, the variable will become available "outside" the scope of the function, effectively becoming a global variable.

def bob():
    global me
    me = "locally defined"   # Defined locally but declared as global
    print me

bob()
print me     # Asking for a global variable

上面的代码会给你:

So the above code will give you:

locally defined
locally defined

另外,由于python的特性,您还可以使用 global 来声明函数,类或本地上下文中的其他对象。虽然我会建议不要这样做,因为如果出现问题或需要调试,它会导致噩梦。

In addition, due to the nature of python, you could also use global to declare functions, classes or other objects in a local context. Although I would advise against it since it causes nightmares if something goes wrong or needs debugging.

这篇关于使用“全球” Python中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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