[英]How can a function access variables that are not defined inside the function?
I recently started studying Python and I came across an example that I did not understand:我最近开始研究 Python,我遇到了一个我不明白的例子:
def teste():
print(a, b)
a = 5
b = 4
teste() # Outputs '5 4'
What is happening here?这里发生了什么? Is
teste()
able to access a
and b
because those variables are globals? teste()
是否能够访问a
和b
因为这些变量是全局变量?
Short answer, yes.简短的回答,是的。
a
and b
are global variables in that sense. a
和b
在这个意义上是全局变量。 Long answer, as long as you keep the variable names on the right side of an assignment or just pass them to a function within a function, they'll act as global variables.答案很长,只要您将变量名称保留在赋值的右侧,或者只是将它们传递给 function 中的 function,它们就会充当全局变量。
What's happening is that Python will first look in the local scope of that function for the variable names and only if it doesn't find them go for the next scope, which is the global scope in your example.发生的事情是 Python 将首先在该 function 的本地 scope 中查找变量名称,并且仅当它没有找到下一个 scope 的 go 时,在您的示例中是全局 scope。
Function foo
has no variable named a
so Python searches in the next available scope Function
foo
没有名为a
变量 so Python 在下一个可用的中搜索 scope
a = "global a"
def foo():
# No variable 'a' in local scope of foo()
# Getting value of 'a' from the scope where foo() is called
print(a)
foo() # Prints "global a"
If you want to declare a variable as global inside your function, you can use the global
keyword.如果要在 function 中将变量声明为全局变量,可以使用
global
关键字。 With that you can set a new value to your now global variable:有了它,您可以为现在的全局变量设置一个新值:
a = "global a"
def foo():
global a
a = "Changed in function"
print(a) # Prints "global a"
foo() # assigns new value to a
print(a) # Prints "Changed in function"
If you don't use the global
keyword, as soon as you use the same variable name inside a function on the left side of an assignment, you are creating a local
variable overshadowing the global
variable with the same name:如果您不使用
global
关键字,一旦您在赋值左侧的 function 中使用相同的变量名称,您就会创建一个local
变量来覆盖具有相同名称的global
变量:
a = "global a"
def foo():
a = "local a"
print(a)
print(a) # Prints "global a"
foo() # Prints "local a"
print(a) # Prints "global a"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.