globals()在Python中的原因? [英] Reason for globals() in Python?

查看:262
本文介绍了globals()在Python中的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中使用globals()函数的原因是什么?它只返回全局变量的字典,这些全局变量已经是全局的,所以它们可以在任何地方使用......我只是出于好奇,试图学习python。



<$ ():
print(globals()[]
$ def F():
global x
x = 1

def G x])#将返回全局'x'的值,即1

def H():
print(x)#将返回全局'x'的值,其中,也是1

F()
G()
H()

我在这里看不到这一点?只有当我需要它的时候,如果我有局部变量和全局变量,它们都有相同的名称

  def F( ):
global x
x = 1

def G():
x = 5
print(x)#5
print(globals ()[x])#1

F()
G()

但是,你永远不应该遇到两个变量同名的问题,并且需要在同一个范围内使用它们。

解决方案

Python为程序员提供了大量用于反思运行环境的工具。 globals()就是其中之一,它可以在调试会话中查看全局作用域实际包含的对象。



我相信它背后的基本原理与使用 locals()来查看函数中定义的变量相同,使用 dir 来查看模块的内容或对象的属性。



来自C ++背景,我可以理解这些东西似乎没有必要。在静态链接的静态类型环境中,它们绝对会是。在这种情况下,在编译时确切知道哪些变量是全局变量,哪些对象将具有哪些成员,甚至哪些名称由另一个编译单元导出。



然而,在动态语言中,这些东西并不固定;它们可以根据代码的导入方式或运行时间进行更改。至少因为这个原因,在调试器中访问这类信息是非常宝贵的。


What is the reason of having globals() function in Python? It only returns dictionary of global variables, which are already global, so they can be used anywhere... I'm asking only out of curiosity, trying to learn python.

def F():
    global x
    x = 1

def G():
    print(globals()["x"]) #will return value of global 'x', which is 1

def H():
    print(x) #will also return value of global 'x', which, also, is 1

F()
G()
H()

I can't really see the point here? Only time I would need it, was if I had local and global variables, with same name for both of them

def F():
    global x
    x = 1

def G():
    x = 5
    print(x) #5
    print(globals()["x"]) #1

F()
G()

But you should never run into a problem of having two variables with same name, and needing to use them both within same scope.

解决方案

Python gives the programmer a large number of tools for introspecting the running environment. globals() is just one of those, and it can be very useful in a debugging session to see what objects the global scope actually contains.

The rationale behind it, I'm sure, is the same as that of using locals() to see the variables defined in a function, or using dir to see the contents of a module, or the attributes of an object.

Coming from a C++ background, I can understand that these things seem unnecessary. In a statically linked, statically typed environment, they absolutely would be. In that case, it is known at compile time exactly what variables are global, and what members an object will have, and even what names are exported by another compilation unit.

In a dynamic language, however, these things are not fixed; they can change depending on how code is imported, or even during run time. For that reason at least, having access to this sort of information in a debugger can be invaluable.

这篇关于globals()在Python中的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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