全局变量和局部变量命名规则_变量范围和LEGB规则

本文介绍了编程中全局变量和局部变量的命名规则,以及LEGB原则,帮助理解不同作用域内变量的使用和访问方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

全局变量和局部变量命名规则

PYTHON开发人员的提示 (TIPS FOR PYTHON DEVELOPERS)

In the beginning, I assume that you know how to define your own functions — but not only that, you know how to write functions with multiple parameters and can return multiple values using tuples.

首先,我假设您知道如何定义自己的函数-不仅如此,您还知道如何编写具有多个参数的函数并可以使用元组返回多个值。

先决条件 (Prerequisites)

If you do not familiar with defining your own function, the article below will give you more information about it.

如果您不熟悉定义自己的函数,则下面的文章将为您提供有关它的更多信息。

We will now discuss the idea of scope in the context of user-defined functions. You have been defining variables in your programs. So far, you have been using these variables without any problems. However, it would be best if you remembered that not all objects you define are always accessible everywhere in a program. This is the idea of scope, which tells you which part of a program an object or a variable may be accessed.

现在,我们将在用户定义函数的上下文中讨论范围的概念。 您一直在程序中定义变量。 到目前为止,您一直在使用这些变量,没有任何问题。 但是,最好记住,并非定义的所有对象始终在程序中的任何地方都可以访问。 这是范围的概念,它告诉您可以访问程序的哪个部分的对象或变量。

The variables or objects, such as functions that are defined in your program, have a name, as does the function.

变量或对象(例如程序中定义的函数)的名称与函数相同。

There are several types of scope. The first one is the global scope, which means that it is defined in the main body of a script. The second one is the local scope. Local scope means that it is defined within a function. Once the function’s execution is done, any variable inside the local scope terminates, which means you cannot access those variables anymore outside of the function definition.

范围有几种类型。 第一个是全局作用域 ,这意味着它是在脚本主体中定义的。 第二个是本地范围 。 局部作用域意味着它是在函数中定义的。 一旦执行完函数,本地作用域内的任何变量都将终止,这意味着您无法再在函数定义之外访问这些变量。

The third is the built-in scope. This consists of variables in the pre-defined built-ins module, which provides by Python, such as print and sum. The last one is enclosing functions, and we will discuss this later in the nested function section.

第三是内置示波器 。 它由预定义的内置模块中的变量组成,该模块由Python提供,例如print和sum。 最后一个是封闭函数 ,稍后我们将在嵌套函数部分中对此进行讨论。

Let’s check out an example here.

让我们在这里查看示例。

Image for post
Author 作者

We define the function and then call it. If we try to access the variable name value before or after function execution, the variable is not accessible. This is because it was defined only within the local scope of the function. The variable value was not defined globally.

我们定义函数,然后调用它。 如果我们尝试在函数执行之前或之后访问变量名称value ,则无法访问该变量。 这是因为它仅在函数的本地范围内定义 。 变量value未全局定义。

What if we define the variable globally before defining and calling the function?

如果在定义和调用函数之前全局定义变量怎么办?

Image for post
Author 作者

In short, any time we call the variable in the global scope, it will access the variable name in the global scope. However, any time we call the variable in the local scope of the function, it will look in the local scope first. That’s why calling square(5) returns results in 25 and not 30.

简而言之,每当我们在全局范围内调用变量时,它将访问全局范围内的变量名称。 但是,每当我们在函数的本地范围内调用变量时,它将首先在本地范围内查找。 这就是为什么调用square(5)返回结果为25而不是30的原因。

If Python cannot find the variable in the local scope, it will then look in the global scope. For example, we access a variablevalue defined globally within the function square. Note that the global value accessed is the value at the time the function is called, not the value when the function is defined. Thus, if we re-assign value and call the function, we see that the new value of value is accessed.

如果Python在本地范围内找不到变量,则它将在全局范围内查找。 例如,我们访问在函数正方形内全局定义的变量value 。 请注意,访问的全局值是调用函数时的值,而不是定义函数时的值。 因此,如果我们重新分配value并调用该函数,则会看到访问了value的新值。

It is clear that when we reference a variable, the local scope is first searched, then the global. The built-in scope is reached if the variable does not exist in the local and global scope. What if we want to alter the value of a global variable within a function call? This is where the keyword global comes in handy.

显然,当我们引用变量时,首先搜索局部范围,然后是全局范围。 如果变量在本地和全局范围中不存在,则将达到内置范围。 如果我们想在函数调用中更改全局变量的值怎么办? 这是关键字global派上用场的地方。

Image for post
Author 作者

Within the function definition, we use the keyword global, followed by the variable name of the global variable that we wish to access and alter. For example, here we change value to its square. After that, we will call the value variable. We see that the global value has indeed been squared by running the function square.

在函数定义中,我们使用关键字global ,后跟我们要访问和更改的全局变量的变量名。 例如,在这里我们将value更改为其平方。 之后,我们将调用value变量。 我们看到,通过运行函数平方,确实实现了全局值的平方。

嵌套函数 (Nested Function)

What if we have a function called inside which is defined inside function outside, and we reference a variable name x in the inside function? The answer is intuitive. Python searches the local scope of the inside function. If it doesn’t find that variable, it searches the scope of the outside function, which is called an enclosing function because it encloses the inside function. If Python can’t find that variable in the enclosing function’s scope, it only then searches the global scope and then the built-in scope.

如果我们有一个名为inside的函数inside该函数outside的函数inside定义,并且在inside函数中引用了变量名x ,该怎么办? 答案很直观。 Python搜索inside函数的本地范围。 如果找不到该变量,它将搜索outside函数的范围,该函数称为封闭函数,因为它将inside函数封闭起来。 如果Python在封闭函数的作用域中找不到该变量,则只会先搜索全局作用域,然后再搜索内置作用域。

Image for post
Author 作者

Why are we nesting a function?

为什么我们要嵌套一个函数?

There are some good reasons. Let’s say that we want to do a process multiple times within a function. For example, we want a function that accepts three numbers as parameters and executes the same function on each of them. One way would be to write out the computation three times, but this does not scale if you want to perform it often. Instead, we can define an inner function within our function definition and call it where required. This is called a nested function.

有一些很好的理由。 假设我们要在一个函数中进行多次处理。 例如,我们想要一个函数,该函数接受三个数字作为参数,并对每个数字执行相同的函数。 一种方法是将计算写出3次,但是如果您想经常执行它就无法扩展。 相反,我们可以在函数定义内定义内部函数,并在需要时调用它。 这称为嵌套函数。

Let’s look at another example here.

让我们在这里看看另一个例子。

Image for post
Author 作者

The syntax for the inside function is the same as that for any other function. In this example, we define a function power_of, which contains an internal function called inside. Now look at what power_of returns: it returns the internal function inside. power_of takes one argument and creates a function inside that returns the nth power of any number. This is a little bit complicated and will be more precise when we execute the function power_of.

inside函数的语法与任何其他函数的语法相同。 在此示例中,我们定义一个函数power_of ,其中包含一个称为inside的内部函数。 现在看看power_of返回什么:它返回内部函数insidepower_of一个参数并inside创建一个函数,该函数返回任意数量的n次幂。 这有点复杂,当我们执行power_of函数时,它将更加精确。

Passing the number 2 to power_of creates a function that squares any number. Likewise, passing the number 3 to power_of creates a function that cubes any number.

将数字2传递给power_of会创建一个对任何数字平方的函数。 同样,将数字3传递给power_of会创建一个对任何数字power_of立方的函数。

One interesting detail is, when we call the function square, it remembers the value n=2, although the enclosing scope defined by power_of and to which n=2 is local, has finished execution. This is a nuance referred to as a closure in Computer Science circles and shouldn’t concern you too much. However, it is worth mentioning, as you may encounter it out there.

一个有趣的细节是,当我们调用函数square ,它记住值n=2 ,尽管power_of定义的且n=2是局部的包围范围已经完成了执行。 这是计算机科学界中被称为闭包的细微差别,不要太在意您。 但是,值得一提的是,您可能会在那里遇到它。

Image for post
Author 作者

Turning into our discussion of scope, you can use the keyword global in function definitions to create and change global variables; similarly, in a nested function, you can use the keyword nonlocal to create and change variables in an enclosing scope.

进入我们关于范围的讨论,您可以在函数定义中使用关键字global来创建和更改全局变量。 同样,在嵌套函数中,可以使用关键字nonlocal在封闭范围内创建和更改变量。

In this example, we modify the value of n in the inside function. Because we used the keyword nonlocal, it changes the value of n in the enclosing scope. This is why calling the outside function prints the value of n as determined within the function inside.

在此示例中,我们在inside函数中修改了n的值。 因为我们使用了关键字nonlocal ,所以它在封闭范围内更改了n的值。 这就是为什么调用outside函数会打印在函数inside确定的n值的原因。

结论 (Conclusion)

Variable references search:

变量引用搜索:

  • Local scope

    当地范围
  • Enclosing functions

    封闭功能
  • Global scope

    全球范围
  • Built-in scope

    内置范围

This is recognized as the LEGB rule, where L is for local, E is for enclosing, G is for global, and B is for built-in. Also, remember that defining variables will only create or change local names, unless they are stated in global or nonlocal statements using the keyword global or the keyword nonlocal.

这被认为是LEGB规则,其中L表示本地,E表示封闭,G表示全局,B表示内置。 另外,请记住,除非在全局或非本地语句中使用关键字global或关键字nonlocal声明变量,否则定义变量只会创建或更改本地名称。

关于作者 (About the Author)

Wie Kiang is a researcher who is responsible for collecting, organizing, and analyzing opinions and data to solve problems, explore issues, and predict trends.

Wie Kiang是一位研究人员,负责收集,组织和分析意见和数据以解决问题,探索问题和预测趋势。

He is working in almost every sector of Machine Learning and Deep Learning. He is carrying out experiments and investigations in a range of areas, including Convolutional Neural Networks, Natural Language Processing, and Recurrent Neural Networks.

他几乎在机器学习和深度学习的每个领域工作。 他正在许多领域进行实验和研究,包括卷积神经网络,自然语言处理和递归神经网络。

Connect on LinkedIn

LinkedIn上 连接

翻译自: https://towardsdatascience.com/scope-of-variable-and-legb-rule-4d44d4576df5

全局变量和局部变量命名规则

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值