全局变量被多个函数改变 - 如何在Python中声明 [英] Global variable changed by multiple functions - how to declare in Python
问题描述
我在多个函数中使用了一些变量。
这包括通过这些函数中的每一个来更改变量值。
我已经在第一个变量中声明变量为'global'函数。
我应该在每个函数中多次声明这个变量为 global
(并且这不会覆盖第一个 global
我在第一个函数中声明的变量)或者我不应该在所有这些函数中再次声明它为 global
(但局部变量仍然会存在看作 global
,因为我已经第一次声明了这个变量)?
global关键字告诉解析器每个函数,一个名称不应该被视为当分配给本地时。
通常您在函数中绑定的任何名称(赋值,用作函数参数,用于导入语句在函数体中等)被解析器视为本地。
通过使用全局
关键字,解析器将代替生成将查找全局名称的字节码。如果您有多个分配给全局的函数,则需要在所有这些函数中声明该名称 global
。然后,他们会在全局名称空间中查找名称。
请参阅 global
语句文档:
< blockquote>
和命名和绑定文档:
如果名称被绑定在一个块中,则它是该块的局部变量。如果名称在模块级绑定,它是一个全局变量。 (模块代码块的变量是局部变量和全局变量)如果一个变量在代码块中使用,但在那里没有定义,它是一个自由变量。
I am using some variable in multiple functions.
This includes changing the variable values by each of those functions.
I already declared the variable as 'global' in the first function.
Should I declare this variable again and again as global
in each function (and this will not overwrite the first global
variable I declared in the first function) or I should not declare it again as global
in all those functions (but the local variables there still will be seen as global
since I already declared this variable so first time)?
The global keyword tells the parser per function that a name shouldn't be treated as a local when assigned to.
Normally any name you bind in a function (assign to, use as a function argument, use in an import statement in the function body, etc.) is seen by the parser as a local.
By using the global
keyword, the parser will instead generate bytecode that'll look for a global name instead. If you have multiple functions that assign to the global, you'll need to declare that name global
in all those functions. They'll then look up the name in the global namespace instead.
See the global
statement documentation:
The
global
statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.
and the Naming and Binding documentation:
If a name is bound in a block, it is a local variable of that block. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.
这篇关于全局变量被多个函数改变 - 如何在Python中声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!