为什么可以在使用变量定义函数之后再定义变量?
我有一个非常简单而且可能很愚蠢的问题:
为什么这有效?
def print_list():
for student in student_list:
print(student)
student_list = ["Simon", "Mal", "River", "Zoe", "Jane", "Kaylee", "Hoban"]
print_list()
按照我了解函数和参数的方式,函数 print_list()
不应该识别 student_list
因为我没有将它指定为函数的参数。
I have a very simple and maybe dumb question:
Why does this work?
def print_list():
for student in student_list:
print(student)
student_list = ["Simon", "Mal", "River", "Zoe", "Jane", "Kaylee", "Hoban"]
print_list()
The way I've come to know functions and arguments, the function print_list()
shouldn't recognize student_list
since I didn't assign it as an argument for the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您调用
print_list()
时,您已将student_list
定义为全局变量。By the time you're calling
print_list()
, you havestudent_list
defined as a global variable.在 Python 中,变量是在您分配变量时创建的。在您的情况下,
student_list
是在全局范围内分配的,因此它是一个全局变量。 (全局作用域是不在函数内部的东西。)当Python在函数内部遇到一个不是局部变量的变量时(也就是说,它没有作为参数传入,也没有在函数内部分配) ,它会自动在全局范围内查找变量。
如果您想知道
global
语句的目的是什么,因为全局变量在函数内部已经可见:global
允许您重新分配全局变量变量,并使其全局生效。例如:在大多数情况下,您不需要
global
语句,我建议您不要使用它,尤其是在您对 Python 更有经验之前。 (不过,即使是经验丰富的 Python 程序员也往往不太使用global
。)In Python, variables are created when you assign them. In your case,
student_list
is assigned in the global scope, so it is a global variable. (The global scope is the stuff that isn't inside your function.)When Python encounters a variable inside a function that is not a local variable (that is, it was not passed in as an argument and was not assigned inside the function), it automatically looks for the variable in the global scope.
If you are wondering what the purpose of the
global
statement is, since global variables are already visible inside functions:global
allows you to reassign a global variable, and have it take effect globally. For example:In most cases, you don't need the
global
statement, and I would recommend that you don't use it, especially until you are much more experienced in Python. (Even experienced Python programmers tend not to useglobal
very much, though.)我的理解是,你的程序有3个部分:
当你调用print_list()时,student_list已经在那里了。此外,在函数中,您具有搜索变量(student_list)的范围:
1.本地范围(它会失败,因为你没有定义它,只是引用)
2.全局范围(它会成功,因为它刚刚初始化
The way I understand it is that your program has 3 parts
When you call print_list(), student_list is already there. Also, in a function you have the scopes where a variable (student_list) is searched:
1. local scope (it'll fail because you don't have it defined, only referred)
2. global scope (it'll succeed, because it was just initialised