简体   繁体   English

Python使用globals()访问全局变量

[英]Python accessing global variables using globals()

Look into below example.. 看下面的例子。

var1 = 10
var2 = "String"
var3 = True
dic = {}

def func1():
  ...
  ...

def main():
  varN = globals().["var1"]
  Dictionary = globals().["dic"].var2('some other string')

How to read this ? 如何阅读? globals () ? 全球()? how is this being used and interpreted ? 这是如何使用和解释的?

Please Help. 请帮忙。 Thanks. 谢谢。

globals() returns a dictionary. globals()返回一个字典。

print type(globals())  # <type 'dict'>

So, subscript notation is enough to access the global variables. 因此,下标符号足以访问全局变量。

print globals()["var1"]
globals()["dic"][var2] = 'some other string'
print dic   # {'String': 'some other string'}

globals is a built in python function it's always available globals是内置的python函数,始终可用
see: http://docs.python.org/2/library/functions.html#globals 请参阅: http : //docs.python.org/2/library/functions.html#globals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM