全局变量是在函数外部定义的变量,可以在整个程序的任何位置访问。在函数内部,可以使用global关键字声明全局变量,在函数内部修改全局变量的值。
global_variable = "This is a global variable." def access_global_variable(): print(global_variable) def modify_global_variable(): global global_variable global_variable = "Modified global variable." access_global_variable() # 输出 "This is a global variable." modify_global_variable() access_global_variable() # 输出 "Modified global variable."
局部变量是在函数内部定义的变量,其只在函数内部可用,如果函数外部想要访问,需要将其作为函数返回值返回。在函数内部想要修改局部变量的值,需要使用global关键字声明。
def access_local_variable(): local_variable = "This is a local variable." print(local_variable) def modify_local_variable(): local_variable = "This is a local variable." print("Before modification: ", local_variable) local_variable = "Modified local variable." print("After modification: ", local_variable) access_local_variable() # 输出 "This is a local variable." modify_local_variable() # 输出 # Before modification: This is a local variable. # After modification: Modified local variable.
函数的参数是在函数定义时指定的,可以在函数内部使用,如果没有使用global声明,其仅在函数内部可用。
def access_parameter(parameter): print(parameter) def modify_parameter(parameter): print("Before modification: ", parameter) parameter = "Modified parameter." print("After modification: ", parameter) access_parameter("This is a parameter.") # 输出 "This is a parameter." modify_parameter("This is a parameter.") # 输出 # Before modification: This is a parameter. # After modification: Modified parameter.
如果在一个函数内部再定义一个函数,那么嵌套函数可以访问其外部函数中定义的变量。在嵌套函数内部,如果修改外部函数的变量,需要使用nonlocal关键字声明。
def outer_function(): outer_variable = "This is an outer variable." def inner_function(): print("Inner function: ", outer_variable) inner_function() outer_function() # 输出 "Inner function: This is an outer variable." def modify_outer_variable(): outer_variable = "This is an outer variable." def inner_function(): nonlocal outer_variable outer_variable = "Modified outer variable." print("Inner function: ", outer_variable) inner_function() print("Outer function: ", outer_variable) modify_outer_variable() # 输出 # Inner function: Modified outer variable. # Outer function: Modified outer variable.
Python函数在其定义和调用期间可以访问全局变量、局部变量、参数以及嵌套函数中的变量名称。在访问和修改变量的时候,需要注意使用global、nonlocal关键字进行声明。
标签: 电商