Python中的全局变量

In this tutorial, We will look into Python Global Variables. We will learn how to define a global variable and then how to access them in a function.

在本教程中,我们将研究Python全局变量。 我们将学习如何定义全局变量,然后如何在函数中访问它们。

Python中的全局变量 (Global Variables in Python)

Global Variables are defined outside a function. We can access a global variable in all parts of the Python program.

全局变量在函数外部定义。 我们可以在Python程序的所有部分中访问全局变量。

Python全局变量示例 (Python Global Variables Example)

Let’s look at a simple example to declare a global variable. Then we will use this global variable in a function.

让我们看一个声明全局变量的简单示例。 然后,我们将在函数中使用此全局变量。

website = "JournalDev.com"


def return_website():
    return website


print(f'My favorite website is {return_website()}')

Output:

输出:

My favorite website is JournalDev.com

The variable “website” is defined in the program, outside of a function. So, it becomes a global variable.

变量“网站”在程序中的函数外部定义。 因此,它成为一个全局变量。

使用全局关键字访问全局变量 (Using global keyword to access global variable)

If there is a variable defined inside a function with the same name, then we have to use global keyword to access the global variable. Otherwise, the local variable value will be used.

如果在函数内部定义了一个具有相同名称的变量,那么我们必须使用global关键字来访问全局变量。 否则,将使用局部变量值。

Let’s look at a quick example to use the global keyword to access global variables.

让我们看一个使用global关键字访问全局变量的简单示例。

website = "JournalDev.com"


def print_website():
    global website
    print(f'My favorite website is {website}')

    website = 'Wikipedia.com'
    print(f'My favorite website is {website}')


print_website()

Output:

输出:

My favorite website is JournalDev.com
My favorite website is Wikipedia.com

If we don’t use the global keyword, the program will throw error message “UnboundLocalError: local variable referenced before assignment”.

如果我们不使用global关键字,则程序将抛出错误消息“ UnboundLocalError:分配前引用的本地变量”。

The best practice is to avoid using the same name as the global variable and stay away from the name conflicts.

最佳做法是避免使用与全局变量相同的名称,并避免名称冲突。

Python globals()函数快速入门 (Quick word on Python globals() function)

Python globals() function return a dictionary representing the current global symbol table. This dictionary contains the global variables name and its values. We can use this function to get quick information on all the global variables.

Python globals()函数返回一个表示当前全局符号表的字典 。 该词典包含全局变量名称及其值。 我们可以使用此功能来获取有关所有全局变量的快速信息。

Python program maintains program information in symbol tables.

Python程序在符号表中维护程序信息。

There are two types of symbol tables:

符号表有两种类型:

  1. Local Symbol Table – stores information related to the local scope of the program.

    本地符号表 –存储与程序的本地范围有关的信息。
  2. Global Symbol Table – stores information related to global scope of the program.

    全局符号表 –存储与程序的全局范围有关的信息。

Python symbol table contains details about variable names, methods, classes, etc.

Python符号表包含有关变量名称,方法, 等的详细信息。

Python globals() function doesn’t accept any arguments.

Python globals()函数不接受任何参数。

print(globals())

Output:

输出:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a99b358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_globals_example.py', '__cached__': None}

It also prints the python script from where this function is called.

它还会在调用此函数的位置打印python脚本。

Let’s see the output if the same function is called from the Python interpreter.

让我们看看是否从Python解释器调用了相同的函数的输出。

$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(globals())
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>>

This time there is no __file__ attribute in the output.

这次输出中没有__file__属性。

globals()字典中的全局变量 (Global Variables in globals() dictionary)

As we mentioned earlier that the global symbol table contains information about the global variables.

如前所述,全局符号表包含有关全局变量的信息。

Let’s see this with a simple example.

让我们用一个简单的例子来看一下。

name = 'Pankaj'

print(globals())

Output:

输出:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a99b358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_globals_example.py', '__cached__': None, 'name': 'Pankaj'}

The global symbol dictionary contains the ‘name’ variable too.

全局符号字典也包含“名称”变量。

One of the features of globals() is that we can modify the variables in the global dictionary. Since it’s a dictionary, we can get the value of a specific key too.

globals()的功能之一是我们可以修改全局字典中的变量。 由于它是字典,因此我们也可以获取特定键的值。

globals()['name'] = 'David'

print(globals()['name'])

Output: David

输出: David

Let’s see if globals() contains local scope variables or not. For this, let’s define a function and some variables inside it.

让我们看看globals()是否包含局部作用域变量。 为此,让我们定义一个函数和其中的一些变量。

def fx():
    local = ''
    global gl
    gl = 'Global'


fx()  # calling fx() to set the variables
print(globals())

print(globals()['gl'])

Output:

输出:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a99b358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_globals_example.py', '__cached__': None, 'name': 'David', 'fx': <function fx at 0x10a9331e0>, 'gl': 'Global'}

Global

The ‘gl’ variable is part of the global dictionary because its scope is global. Whereas, ‘local’ variable is not part of the global dictionary because of having local scope.

'gl'变量是全局词典的一部分,因为它的范围是全局的。 而“局部”变量由于具有局部范围,因此不属于全局词典。

结论 (Conclusion)

Python global variables are very easy to define and use. The globals() function returns the global variables and it can be used in debugging the code. We can use it to identify the global scope variables and functions available to the program. We can also modify the global variable data, but that is not advisable and mostly not required in normal programs.

Python全局变量非常易于定义和使用。 globals()函数返回全局变量,可用于调试代码。 我们可以使用它来识别程序可用的全局范围变量和函数。 我们还可以修改全局变量数据,但这是不可取的,并且在正常程序中通常不是必需的。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22870/global-variables-python

  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值